[英]How to search the whole string for a specific word?
我有这个代码,它搜索一个字符串数组并在输入字符串匹配字符串的第一个字符时返回结果:
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]);
}
}
}
但是我想在输入字符串不仅匹配第一个字符而且匹配字符串中的任何位置的地方也获取这些字符串? 这个怎么做?
您可以通过三种方法来搜索字符串是否包含子字符串:
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
我没有足够的“声誉点”在评论中回复,但接受的答案中有错误。 indexOf() 在找不到子字符串时返回 -1,所以它应该是:
b = string.indexOf("I am") >= 0;
试试这个-
etsearch.getText().toString().contains((String) countryCode[i]);
你可以使用包含。 如:
myString.contains("xxx");
另请参阅: http : //docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html ,特别是包含区域。
使用以下内容:
public boolean contains (CharSequence cs)
从:API 级别 1
确定此 String 是否包含传递的 CharSequence 中的字符序列。
Parameters
cs
要搜索的字符序列。
Returns
如果此字符串中包含字符序列,则为true ,否则为false
实际上,android 中默认的 Arrayadapter 类似乎只是从整个单词的开头进行搜索,但是通过使用自定义 Arrayadapter 类,您可以搜索任意字符串的一部分。 我已经创建了整个自定义类并发布了库。 这是非常容易使用。 您可以从此处或通过单击下面提供的链接来检查实施和使用情况。
https://github.com/mohitjha727/Advanced-Search-Filter
你可以参考这个简单的例子——我们有名字“Mohit”和“Rohan”,如果我们输入“M”,那么Mohit就会出现在搜索结果中,但是当我们输入“oh”时,Mohit和Rohan都会出现在搜索结果中有共同的字母“哦”。
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.