我有这个代码搜索字符串数组,如果输入字符串匹配字符串的第1个字符,则返回结果:
for (int i = 0; i < countryCode.length; i++) {
if (textlength <= countryCode[i].length()) {
if (etsearch
.getText()
.toString()
.equalsIgnoreCase(
(String) countryCode[i].subSequence(0,
textlength))) {
text_sort.add(countryCode[i]);
image_sort.add(flag[i]);
condition_sort.add(condition[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我想得到那些字符串,输入字符串不仅匹配在第一个字符,而且在字符串中的任何位置?这该怎么做?
ρяσ*_*я K 25
您有三种方法可以搜索字符串是否包含子字符串:
String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0; // true if contains
// Anywhere in string
b = string.matches("(?i).*i am.*"); // true if contains but ignore case
// Anywhere in string
b = string.contains("AA") ; // true if contains but ignore case
Run Code Online (Sandbox Code Playgroud)
我没有足够的"声望点"在评论中回复,但在接受的答案中有错误.indexOf()在找不到子字符串时返回-1,所以应该是:
b = string.indexOf("I am") >= 0;
Run Code Online (Sandbox Code Playgroud)