0
How to check given string in array or not?
Java
3 Réponses
+ 4
You could use Arrays.binarySearch() (Requires an ordered array)
Returns index of string that matches, or a negative number if not found.
An example:
import java.util.Arrays;
public class ExampleOfIndexOf {
public static void main (String args[]) {
String[] stringArray = {"hair", "eye", "mouth", "nose"};
Arrays.sort(stringArray);
System.out.println(Arrays.binarySearch(stringArray, "mouth")); // 2
System.out.println(Arrays.binarySearch(stringArray, "mou")); // -3 in this case: -(array length - 1)
}
}
+ 3
bahha If you need to compare string content, use .equals() instead of == :)
Check this example:
https://code.sololearn.com/cXXyWUUC6FXE/?ref=app
+ 2
here is a primitive and less efficient way to do it.
public class Program
{
public static void main(String[] args) {
String str = "yyy";
String array [] = {"yyy"};
for(int i = 0; i < array.length ; i++){
if(array[i] == str ){
System.out.println("found");
} else{
System.out.println(" not found");
}
}
}
}