简体   繁体   English

在不使用正则表达式的情况下检查String是否包含String []中存在的任何值-Java

[英]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. 我有一个String [],其值需要在输入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[]? 现在,如果我输入MMMDCCIV ,如何检查字符串是否具有String []中的任何值? or is iterating through the String[] and checking for each value among the string entered, is good enough approach? 还是遍历String []并检查输入的字符串中的每个值,是否足够好?

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? 还是有更好的方法?

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. 遍历数组是唯一的方法(尽管使用Java 8 Streams可以用更少的代码编写数组),但是循环中存在错误。 You should only return false after the loop ends without finding any match. 您应仅在循环结束后返回false而不找到任何匹配项。

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). 假设您需要至少一个数组元素包含在输入String中(而不是全部包含)。

Instead of iterating over the array, you could iterate over the input String after adding the knownCombinations to a Set : 除了遍历数组之外,还可以在将knownCombinations添加到Set之后遍历input String:

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. 这本质上是@Eran解决方案的逆过程。 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. 我可能会选择他的方法,因为它比较容易阅读,但我认为我的回答是尝试以不同的方式解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM