0

How to check given string in array or not?

Java

26th Feb 2019, 2:25 PM
Mohammad Umair
Mohammad Umair - avatar
3 Answers
+ 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) } }
26th Feb 2019, 4:15 PM
unChabon
unChabon - avatar
+ 3
bahha If you need to compare string content, use .equals() instead of == :) Check this example: https://code.sololearn.com/cXXyWUUC6FXE/?ref=app
26th Feb 2019, 5:11 PM
unChabon
unChabon - avatar
+ 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"); } } } }
26th Feb 2019, 2:52 PM
Bahha┣
Bahha┣ - avatar