我是Android和Java的新手,所以请保持友好:)
我的EditText
应用程序中有一个,用于在其中搜索特定的字符串String[]
我的代码运行良好,但不是我想要的:
ArrayList<String> allProd = new ArrayList<String>;
ArrayList<String> allProd_sort = new ArrayList<String>;
allProd = [the table is brown, the cat is red, the dog is white];
String[] allProdString = allProd.toArray(new String[allProd.size()]);
...
//inputSearch is the EditText
inputSearch.addTextChangeListener (new TextWatcher() {
...
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
int textLength = inputSearch.getText().length();
String text = inputSearch.getText().toString();
for (int y = 0; y< allProdString.length; y++) {
//in my case i want that the search start when there are min 3 characters in inputSearch
if(textLength <= allProdString[y].length() && textLength >=3) {
if (Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE)
.matcher(allProdString[y]).find()) {
allProd_sort.add(allProdString[y]);
}
}
}
}
});
此代码产生以下结果:
如果我搜索“表是” =>allProd_sort
将[the table is brown]
但是如果我搜索“ table brown” =>allProd_sort
将为空,但我想要[the table is brown]
我该如何改善呢?
谢谢大家
好的-第一个优化:如果您的初始要求(Searchtext> = 3)为true,则仅进入循环:
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
int textLength = inputSearch.getText().length();
if (textLength < 3) return;
String[] searchPattern = inputSearch.getText().toString().toLowerCase().split("\\s+");
for (int y = 0; y< allProdString.length; y++) {
if(textLength <= allProdString[y].length()) {
if (matchSearch(allProdString[y].toLowerCase(), searchPattern)) {
allProd_sort.add(allProdString[y]);
}
}
}
如果只想匹配所有单词都包含在相同序列中的行,则可以像Tim B所说的那样简单地创建一个正则表达式。
但是,如果您还想匹配包含单词的字符串,则在任何地方搜索search“ brown table”-> [the table is brown],那么您需要一个小循环:
public boolean matchSearch(String s, String[] searches) {
for (String search : searches) {
if (!s.contains(search) return false; // If the word is not in the string FALSE
}
return true; // If all words were found in the string, it is a match!
}
为了更清楚一点-> brown。* table只匹配table出现在brown之后的字符串...我不认为您可以轻松地创建高效的RegEx来检查每个单词是否在字符串中的任何位置至少一次...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句