-5

I was hoping someone could help. Well I know how to use linear search to find a numerical value inside of an array. But now I want to learn how to search a string array for a string.

For example if I have a string array of students names how could I search the array to find a specific name inside that array?

If someone could write me a simple example since I'm new to Java still. Thank you, also is there a better way to search these kinds of things or linear search fine? :)

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
shrillhook
  • 37
  • 3
  • 1
    When you say "help" but show no effort, people interpret that as "do it for me" which is why you're getting downvoted. "write me a simple example" probably didn't help either. Please make some effort before asking next time as this is not a free coding service. – tnw May 02 '16 at 17:05

2 Answers2

2

Use Arrays.asList() to wrap the array in a List. Then search in the List using contains() method:

String[] a= {"is", "are", "then"};
Arrays.asList(a).contains("are");

You can do using arrays also, but have to write some more lines of code. contains() method also does the linear search only.

public static boolean useLoop(String[] arr, String targetValue) {
    for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }
    return false;
}
FallAndLearn
  • 4,035
  • 1
  • 18
  • 24
0

The code for Strings can be the same as for numerical values, except you should use the String class's equals(...) method instead of ==.

You should use equals(...) because it's possible for two different String objects to have the same characters. But == would be incorrect because they are different objects.

Examples comparison expressions:

myArray[i].equals(myString)

or

myString.equals(myArray[i]) 

Note: Be sure the part on the left side isn't null. Otherwise you will get a NullPointerException.

Bobulous
  • 12,967
  • 4
  • 37
  • 68
fritz314
  • 1
  • 1