How can I tell if the substring "template" (for example) exists inside a String object?
如何判断字符串对象中是否存在子字符串“template”(例如)?
It would be great if it was not a case-sensitive check.
如果它不是一个区分大小写的检查,那就太好了。
4 个解决方案
#1
Use a regular expression and mark it as case insensitive:
使用正则表达式并将其标记为不区分大小写:
if (myStr.matches("(?i).*template.*")) {
// whatever
}
The (?i) turns on case insensitivity and the .* at each end of the search term match any surrounding characters (since String.matches works on the entire string).
(?i)打开不区分大小写,搜索项每端的。*匹配任何周围的字符(因为String.matches适用于整个字符串)。
#2
For a case insensitive search, to toUpperCase or toLowerCase on both the original string and the substring before the indexOf
对于不区分大小写的搜索,在indexOf之前的原始字符串和子字符串上的toUpperCase或toLowerCase
String full = "my template string";
String sub = "Template";
boolean fullContainsSub = full.toUpperCase().indexOf(sub.toUpperCase()) != -1;
#3
You can use indexOf() and toLowerCase() to do case-insensitive tests for substrings.
您可以使用indexOf()和toLowerCase()对子字符串执行不区分大小写的测试。
String string = "testword";
boolean containsTemplate = (string.toLowerCase().indexOf("template") >= 0);
#4
String word = "cat";
String text = "The cat is on the table";
Boolean found;
found = text.contains(word);
#1
Use a regular expression and mark it as case insensitive:
使用正则表达式并将其标记为不区分大小写:
if (myStr.matches("(?i).*template.*")) {
// whatever
}
The (?i) turns on case insensitivity and the .* at each end of the search term match any surrounding characters (since String.matches works on the entire string).
(?i)打开不区分大小写,搜索项每端的。*匹配任何周围的字符(因为String.matches适用于整个字符串)。
#2
For a case insensitive search, to toUpperCase or toLowerCase on both the original string and the substring before the indexOf
对于不区分大小写的搜索,在indexOf之前的原始字符串和子字符串上的toUpperCase或toLowerCase
String full = "my template string";
String sub = "Template";
boolean fullContainsSub = full.toUpperCase().indexOf(sub.toUpperCase()) != -1;
#3
You can use indexOf() and toLowerCase() to do case-insensitive tests for substrings.
您可以使用indexOf()和toLowerCase()对子字符串执行不区分大小写的测试。
String string = "testword";
boolean containsTemplate = (string.toLowerCase().indexOf("template") >= 0);
#4
String word = "cat";
String text = "The cat is on the table";
Boolean found;
found = text.contains(word);