Sil*_*ver 16 java string substring contains
你好伙伴们!我正在尝试创建一个程序,以尽可能快地检测字符串中是否有多个单词,如果是,则执行一个行为.最好,我希望它能够检测这些单词的顺序,但只有这样才能快速完成.到目前为止,这就是我所做的:
if (input.contains("adsf") && input.contains("qwer")) {
execute();
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,为多个单词执行此操作会变得很烦人.这是唯一的方法还是有更好的方法来检测多个子串?有没有办法检测订单?
Chr*_*sch 34
我会用以下词语创建一个正则表达式:
Pattern pattern = Pattern.compile("(?=.*adsf)(?=.*qwer)");
if (pattern.matcher(input).find()) {
execute();
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅以下答案:https://stackoverflow.com/a/470602/660143
Lin*_*nus 10
在 Java 8 中你可以做
public static boolean containsWords(String input, String[] words) {
return Arrays.stream(words).allMatch(input::contains);
}
Run Code Online (Sandbox Code Playgroud)
示例用法:
String input = "hello, world!";
String[] words = {"hello", "world"};
if (containsWords(input, words)) System.out.println("Match");
Run Code Online (Sandbox Code Playgroud)
你可以使用一个数组:
String[] matches = new String[] {"adsf", "qwer"};
bool found = false;
for (String s : matches)
{
if (input.contains(s))
{
execute();
break;
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个有效的,因为你发布的,但更易于维护.寻找更有效的解决方案听起来像微优化,在被证明是有效的代码瓶颈之前应该被忽略,无论如何使用巨大的字符串集,解决方案可能是一个特里.
| 归档时间: |
|
| 查看次数: |
53003 次 |
| 最近记录: |