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

标签 java regex

我正在制作一个简单的程序来查找给定字符串中的所有单词并将所有唯一单词放入数组列表中。 (与 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/

相关文章:

C# 正则表达式匹配包含已知子字符串且不等于特定关键字的单词

Javascript RegEx - 无效量词

json - 具有 (RegEx) 模式的 json-schema 中的枚举

java - 我们如何使用 Java 迭代大小约为 2 gb 的 JSON 文件

java - 为什么在一个 Set 上使用 FetchType.LAZY 时会出现 LazyInitializationException,而在另一 Set 上则不会?

java - 创建从不与java重叠的图形对象

java - 部署到 sonatype nexus 存储库失败并缺少资源

java - 正则表达式忽略不同行上两个字符之间的字符

java - Autowiring 依赖项注入(inject)失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException 如何解决它

PHP:将 preg_replace 与 htmlentities 结合使用