gpt4 book ai didi

Java 单词查找器程序无法捕获字符串中的所有唯一条目

转载 作者:行者123 更新时间:2023-11-30 03:12:13 25 4
gpt4 key购买 nike

我正在制作一个简单的程序来查找给定字符串中的所有单词并将所有唯一单词放入数组列表中。 (与 Python 中的 list.sort() 对列表的作用差不多)。

在我给定的测试输入中,程序会跳过一个单词。如果能够了解为什么它没有捕捉到所有单词,我将非常感激。

这是我的代码:

public class wordFinder {
public static void main(String[] args) {
String input = "This is a test This is a test This is a test This is a test This is another test This is not a test";
ArrayList<String> wordList = new ArrayList<>();
Pattern pattern = Pattern.compile("\\w+");
Matcher match = pattern.matcher(input);
while(match.find()) {
wordList.add(match.group());
}
System.out.println(wordList);
for (int i = 0; i < wordList.size(); i++){
for(int q = i; q< wordList.size(); q++){
if(wordList.get(i).equals(wordList.get(q))){
wordList.remove(q);
}
else continue;
}

}
System.out.println(wordList);
}

}

附注我知道正则表达式和模式/匹配器并不是真正需要的,因为我可以分割字符串。我这样做是因为我正在考虑稍后扩展我的程序以搜索多个特定的事物。

最佳答案

这是一个比添加然后删除更好的选项。另外,就像我说的,你会用这个做什么?如果您将它用于单词库,您可能需要考虑其他结构!

  public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
String input = "This is a test This is a test This is a test This is a test This is another test This is not a test";
String [] tokens = input.split("\\s");
for(int i = 0; i < tokens.length; ++i){
if(!list.contains(tokens[i])){
list.add(tokens[i]);
}
}
System.out.println(list);
}

关于Java 单词查找器程序无法捕获字符串中的所有唯一条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33397622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com