所以,我想从字符串到字符串数组进行比较
String [] string = new String [10];
string [1] = "pencil";
string [2] = "pen";
string [3] = "eraser";
如何将字符串与上面的字符串数组进行比较?
答案 0 :(得分:2)
更快捷的方法是使用此代码
if(Arrays.asList(string).contains(search_string))
答案 1 :(得分:1)
如果我理解正确的话,写一个循环,迭代多个字符串(示例数组)并与src字符串相等。
String [] string = new String [10];
...
String src = ..;//src string
for(String string : string){
if(src.equals(string)){
//Equal
}
}
答案 2 :(得分:0)
尝试使用:
for (int i = 0; i < string.length; i++) {
if (ch.equals(string[i])) { // ch is the string to compare
System.out.println("equal");//or whatever your action is
}
}
修改强>
如果您要做的是验证搜索到的字符串是否出现在字符串[i]中,您可以尝试:
string[0] = "pentagon";
string[1] = "pencil";
string[2] = "pen";
string[3] = "eraser";
string[4] = "penny";
string[5] = "pen";
string[6] = "penguin";
string[7] = "charp";
string[8] = "charpen";
string[9] = "";
String ch = "pen";
然后测试数组元素是否包含搜索的字符串:
for (int i = 0; i < string.length; i++) {
if (string[i].indexOf(ch) != -1) {
System.out.println(string[i]+" contains "+ch);
} else
System.out.println(string[i]+" doesn't contain "+ch);
}
编辑2:
int i=0;
Boolean found=false;
while(i < string.length && !found) {
if (string[i].indexOf(ch) != -1) {
found=true;
}
i++;
}
if(found){
system.out.println(ch+" is found");
}