Reputation: 344
How can i check if a string matches any of elements in string array.
Suppose a String array contain {abcdef, ghijkl} Comparing it with a string "abc" should return the first value
If have been using stringArray.contains(string)
method but it seems to work only if the complete string matches. I need to get the result even if the string partially matches
Any help would be appreciated
Upvotes: 2
Views: 373
Reputation: 28289
You can use indexOf
method:
String[] contains(String[] stringArray, String target) {
String[] result = new String[2];
for(int index = 0; index < stringArray.length; index++) {
String current = stringArray[index];
if (s.indexOf(target) >= 0) {
result[0] = current;
result[1] = String.valueOf(index);
}
}
}
Upvotes: 1
Reputation: 140613
Streams come in handy:
Arrays.stream(stringArray)
.filter(s -> s.contains(stringToSearch))
.findFirst();
Of course, your requirements boil down to: find the first string in the array that starts with the search string. But actually your requirements are a bit unclear, so you should apply the filter as required. There is a big difference between contains()
and startsWith()
for example!
Upvotes: 2
Reputation: 453
No method without using a loop. I understand you might be looking for some implementation which does not need a self written loop. But you have to loop.
Upvotes: 2