So, I want to compare from string to array of strings
String [] string = new String [10];
string [1] = "pencil";
string [2] = "pen";
string [3] = "eraser";
how do i compare string to the array of strings from above?
So, I want to compare from string to array of strings
String [] string = new String [10];
string [1] = "pencil";
string [2] = "pen";
string [3] = "eraser";
how do i compare string to the array of strings from above?
A quicker way is to use this code
if(Arrays.asList(string).contains(search_string))
If I understand you correctly, Write a loop, where iterate multiple string(example array) and equals with src string.
String [] string = new String [10];
...
String src = ..;//src string
for(String string : string){
if(src.equals(string)){
//Equal
}
}
Try using this:
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
}
}
EDIT:
If what you are seeking to do is to verify if the searched string appears in the string[i] you can try:
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";
Then test if the arrays elements contain the searched string:
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);
}
EDIT 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");
}