比较 Java 中的字符串数组值

Compare string array values in Java

我正在尝试将字符串数组中的每个值与同一数组的所有值进行比较,看它们是否相等(类似于 "wordA" 等于 "wordA")。 这就是我所拥有的:

FileReader input; 

input = new FileReader("file.txt"); 

BufferedReader reader = new BufferedReader(input); 

String line = reader.readLine(); 

String[] text = line.replaceAll("[^a-zA-Z ]", "").split("\s+"); 

for (int A = 0; A < text.length; A++) {

    for (int B = text.length; B > 0; B++){

        if (text[A].equals(text[B])){ 

        System.out.println("Repeated Word: "+text[A]);  

        }

    } 
} 

只是比较数组spaces,所以如果A和B=3(例如),它总是为真,忽略这个space里面的字符串。所以我得到了文本中所有单词的输出。

第二个for-loop错误,你会得到一个数组索引越界

相反,您也应该从头开始,如果索引相等则排除

String[] text = { "a", "b", "c", "d", "a" };
for (int a = 0; a < text.length; a++) {
  for (int b = 0; b < text.length; b++) {
    if (text[a].equals(text[b]) && a != b) {
      System.out.println("Reapeated word : " + text[a]);
    }
  }
}

或者按照评论中的建议,从数组中的下一个元素开始(在这种情况下,您不必检查索引是否相等)

String[] text = { "a", "b", "c", "d", "a" };
for (int a = 0; a < text.length; a++) {
  for (int b = a + 1; b < text.length; b++) {
    if (text[a].equals(text[b])) {
      System.out.println("Reapeated word : " + text[a]);
    }
  }
}

看起来嵌套循环应该是 B-- 而不是 B++。那不是一个永无止境的循环吗?无论哪种方式,我认为没有理由在每个循环中以相反的方向迭代。但对每个人来说。

此外,应该进行某种比较以确保 A != B,否则您将比较数组中的相同值。 if (text[A].equals(text[B])) 会在某些时候比较 if (text[0].equals(text[0]))if (text[1].equals(text[1]))

对于数组中的每个元素,这总是 return 至少一次为真。

您需要添加 if (A != B) 的比较来修复它。

像这样:

for (int A = 0; A < text.length; A++) {
  for (int B = 0; B < text.length; B++) {
    if (A != B && text[A].equals(text[B])) {
         System.out.println("Repeated word:" + text[A]);
    }
  }
}