改进EditText中的搜索字符串

时间:2014-06-24 15:53:21

标签: android string search android-edittext

我需要改进EditText的系统搜索字符串。目前我有这个例子:

要搜索的字符串 - > Museo Nacional del Prado

如果我搜索这些字符串,则会找到它们:

  • Museo Nacional
  • 普拉多

如果我搜索此字符串,则找不到:

  • 普拉多博物馆

如何调试代码以查找Museo del Prado?感谢

@Override
public void afterTextChanged(Editable s) {

    filterArray.clear();
    searchString = edittextBuscar.getText().toString().trim();

    String cadenaBuscar = reemplazarCaracteres(searchString);

    if (items.size() > 0 && cadenaBuscar.length() > 0) {

        for (Items name : items) {

            String cadenaItem = reemplazarCaracteres(name.getNombre());

            if (cadenaItem.toLowerCase(Locale.getDefault()).contains(cadenaBuscar.toLowerCase(Locale.getDefault()))) {

                filterArray.add(name);
            }
        }
        setAdapterToListview(filterArray);
    } else {
        filterArray.clear();
        setAdapterToListview(items);
    }
}

private static String reemplazarCaracteres(String cadena) {

    String original = "áàéèíìóòúùüÁÀÉÈÍÌÓÒÚÙÜñÑçÇ";
    String ascii = "aaeeiioouuuAAEEIIOOUUUnNcC";

    String cadenaLimpia = cadena;

    for (int i = 0; i < original.length(); i++) {

        cadenaLimpia = cadenaLimpia.replace(original.charAt(i), ascii.charAt(i));
    }
    return cadenaLimpia;
}

1 个答案:

答案 0 :(得分:0)

Museo Nacional del Prado 不包含普拉多博物馆

您需要搜索所有子字符串

String reference = "Museo Nacional del Prado";
String toSearch = "Museo del Prado";

StringTokenizer strk = new StringTokenizer(toSearch, " ", false);
boolean matchingResult = true;
while(strk.hasMoreTokens()){
    if(reference.contains(strk.nextToken()) == false){
        matchingResult = false;
        break;
    }
}
System.out.println(matchingResult); 

寻找&#34; Museo del Prado&#34;然后将返回true

您可以添加此方法:

private boolean match(String reference, String toSearch){
    StringTokenizer strk = new StringTokenizer(toSearch, " ", false);
    boolean matchingResult = true;
    while(strk.hasMoreTokens()){
        if(reference.contains(strk.nextToken()) == false){
        matchingResult = false;
        break;
    }
    return matchingResult;
}

并称之为:

String cadenaItem = reemplazarCaracteres(name.getNombre());

if(match(cadenaItem.toLowerCase(Locale.getDefault()), cadenaBuscar.toLowerCase(Locale.getDefault())     )) {
    filterArray.add(name);
}