【发布时间】:2010-10-15 19:30:51
【问题描述】:
如何判断子字符串“模板”(例如)是否存在于 String 对象中?
如果不是区分大小写的检查就好了。
【问题讨论】:
如何判断子字符串“模板”(例如)是否存在于 String 对象中?
如果不是区分大小写的检查就好了。
【问题讨论】:
对于不区分大小写的搜索,在 indexOf 之前的原始字符串和子字符串上都使用 toUpperCase 或 toLowerCase
String full = "my template string";
String sub = "Template";
boolean fullContainsSub = full.toUpperCase().indexOf(sub.toUpperCase()) != -1;
【讨论】:
您可以使用 indexOf() 和 toLowerCase() 对子字符串进行不区分大小写的测试。
String string = "testword";
boolean containsTemplate = (string.toLowerCase().indexOf("template") >= 0);
【讨论】:
使用正则表达式并将其标记为不区分大小写:
if (myStr.matches("(?i).*template.*")) {
// whatever
}
(?i) 开启不区分大小写,并且搜索词两端的 .* 匹配任何周围的字符(因为 String.matches 作用于整个字符串)。
【讨论】:
String word = "cat";
String text = "The cat is on the table";
Boolean found;
found = text.contains(word);
【讨论】:
public static boolean checkIfPasswordMatchUName(final String userName, final String passWd) {
if (userName.isEmpty() || passWd.isEmpty() || passWd.length() > userName.length()) {
return false;
}
int checkLength = 3;
for (int outer = 0; (outer + checkLength) < passWd.length()+1; outer++) {
String subPasswd = passWd.substring(outer, outer+checkLength);
if(userName.contains(subPasswd)) {
return true;
}
if(outer > (passWd.length()-checkLength))
break;
}
return false;
}
【讨论】: