您能否看一下我的代码,并告诉我为什么它不能按预期工作-
String word1 = "Simple sentence that is first";
String word2 = "Another sentence that is second.";
appear(word1, word2);
}
static void appear(String word1, String word2){
String[] split = word1.split(" ");
String[] split2 = word2.split(" ");
for (int i = 0; i <= split.length - 1; i++){
for (int j = 0; j <= split2.length - 1; j++){
if (!split[i].equals(split2[j])){
System.out.println(split[i]);
}
}
}
}
输出应该是:Simple和first,因为它们是第二个句子中没有出现的仅有的两个词。我的输出是第一句话中的所有单词重复了几次。 (!.equals)应该工作吗?
答案 0 :(得分:1)
通过这种方式,您正在检查第一个句子的每个单词是否等于第二个句子的每个单词。举例来说,这意味着对于句子一词,它将检查它是否与另一个相等,如果不相等,将进行porint,然后将其检查是否与句子相等,依此类推。如果要打印,则应跟踪第二句中是否出现第一句话的单词
String word1 = "Simple sentence that is first";
String word2 = "Another sentence that is second.";
appear(word1, word2);
}
static void appear(String word1, String word2){
String[] split = word1.split(" ");
String[] split2 = word2.split(" ");
boolean appeared;
for (int i = 0; i <= split.length - 1; i++){
appeared = false;
for (int j = 0; j <= split2.length - 1; j++){
if (split[i].equals(split2[j])){
appeared = true;
}
}
if(appeared == false)
System.out.println(split[i]);
}
}
答案 1 :(得分:1)
字符串具有contains()方法,您可以依靠它搜索第一句中的每个单词是否出现在第二句中。
String[] split = word1.split(" ");
for (int i = 0; i <= split.length - 1; i++){
if(!Arrays.asList(word2.split(" ")).contains(split[i])){
System.out.println(split[i]);
}
}
使用Java8流,可以将上述内容修改为以下一行。
Arrays.asList(word1.split(" ")).stream().filter(x->!Arrays.asList(word2.split(" ")).contains(x)).forEach(System.out::println);
答案 2 :(得分:1)
解决问题的关键是一个称为Set的数据结构。 GeeksForGeeks的介绍很好。
使用集合,我们可以将问题建模为两组字符串之间的差异。 我试图与Geeks for Geeks文章一致地命名变量,以便您可以继续学习。
Set<String> a = new HashSet<>();
Set<String> b = new HashSet<>();
a.addAll(word1.split(" "));
// a is now {"Simple" "sentence" "that" "is", "first"}
b.addAll(word2.split(" "));
// b is now {"Another", "sentence", "that", "is", "second";
// We can now calculate the difference
a.removeAll(b);
// a is now {"Simple", "first"}
// Because sets are iterable we can finish via a for-each loop
for(String s : a) {
System.out.println(s);
}