Java 查找数组中的字符串是否存在于另一个数组中
我有一个数组Java 查找数组中的字符串是否存在于另一个数组中,java,arrays,string,Java,Arrays,String,我有一个数组String[]questions={“可爱”、“可爱”、“冒险”}
String[]questions={“可爱”、“可爱”、“冒险”}我还有一个数组t[],其中包含所有形容词。我想在array t[]中找到“可爱、可爱、冒险”这几个词。到目前为止,我有这行代码,但它似乎不工作。有人能帮我吗
String u = sn.nextLine();
String[] t = u.split(" ");
for (y = 0; y <= question.length; y++) {
for (int w = 0; w < t.length; w++) {
if (t[w].equals(question[y])) {
System.out.print(t[w] + " ");
break;
}
}
}
String u=sn.nextLine();
字符串[]t=u.split(“”);
对于(y=0;yDo:
这张照片是:
adorable able
那么这个呢:
Set<String> s1 = new HashSet<String>(Arrays.asList(t));
Set<String> s2 = new HashSet<String>(Arrays.asList(questions));
s1.retainAll(s2);
[冒险,可爱]
另一种解决方案是使用数据结构,例如ArrayList或LinkedList,而不是数组
这样,您就可以调用contains().外部for
中的终止条件不正确,并且将超出问题
数组的范围:使用仅当您对性能完全漠不关心时才可以。它可以通过与您的形容词词典的大小相称的因子加速,并且代码更少。“似乎不起作用”怎么办?我试着调试它,但它没有给我任何输出。我删除了=但它仍然没有产生任何输出。我删除了等号,但它仍然没有产生任何输出:/确保u
变量不是空的。我试着调试它,变量u不是空的。因此字符串[]谢谢你的帮助!我真的很感激。事实上,问题中的字符串已经存在于t中。我只是试着调试程序,看看它是否正常工作。我应用了你建议的,但它没有给我任何输出
adorable able
Set<String> s1 = new HashSet<String>(Arrays.asList(t));
Set<String> s2 = new HashSet<String>(Arrays.asList(questions));
s1.retainAll(s2);
String[] t = "Hello, world! I am adventurous and adorable!".split("\\W+");
String[] questions = {"adorable", "able", "adventurous"};
Set<String> s1 = new HashSet<String>(Arrays.asList(t));
Set<String> s2 = new HashSet<String>(Arrays.asList(questions));
s1.retainAll(s2);
System.out.println(s1);
[adventurous, adorable]
for(String question: questions){
for(String word: t){
if(question.equals(word)){
//Do somethin
}
}
}