Vamsi Challa
Vamsi Challa

Reputation: 11109

Check if String contains any of the values present in String[] without using regex - Java

I have a String[] that has values that i need to find in the text entered into an EditText. I know how to do it using regex, but is there a way i can do it without regex.

public static String[] knownCombinations = new String[] { "IV", "IX", "XL",
            "CD", "CM" };

Now, if i enter, MMMDCCIV, how do I check if the string has any of the values from the String[]? or is iterating through the String[] and checking for each value among the string entered, is good enough approach?

For example:

String input = "MMMDCCIV";

for(int i = 0; i < knownCombinations.length; i++) {
  if(input.contains(knownCombinations[i])
    return true;
  else 
    return false;
}

or is there a better approach?

Upvotes: 1

Views: 553

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521629

Instead of iterating over the array, you could iterate over the input String after adding the knownCombinations to a Set:

Set<String> knownSet = new HashSet<String>(Arrays.asList(knownCombinations)); 
String input = "MMMDCCIV";

for (int i=0; i < input.length-1; ++i) {              // iterate over each 2-letter 
    if (knownSet.contains(input.substring(i, i+2)) {  // combination in the input
        return true;
    }
}
return false;

This is essentially the inverse of @Eran 's solution. I would probably go with his approach because it is slightly easier to read, but I thought my answer was a good attempt to solve the problem with a different flavor.

Upvotes: 2

Eran
Eran

Reputation: 393866

Iterating over the array is the only way (though it may be written with less code using Java 8 Streams), but there's an error in your loop. You should only return false after the loop ends without finding any match.

for(int i = 0; i < knownCombinations.length; i++) {
  if(input.contains(knownCombinations[i])
    return true;
}
return false;

That's assuming you require at least one of the array's elements to be contained in the input String (and not all of them).

Upvotes: 2

Related Questions