如何在数组中搜索字符串的一部分? [英] How to search an array for a part of string?

查看:50
本文介绍了如何在数组中搜索字符串的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 arraylist 单词.我使用 Collections.sort(wordsList);

I have an arraylist<string> of words. I sort it using Collections.sort(wordsList);

我使用这个数组作为自动建议下拉框,这样当用户输入一个字母时,他们会得到一个与他们正在输入的内容相似的建议列表.

I'm using this array for an auto-suggest drop down box, so that when the user is typing in a letter, they are given a list of suggestions similar to what they are typing in.

我如何在这个数组中搜索字符串的前缀,比如用户输入mount"?并且数组包含单词mountain",我如何搜索这个数组并返回相似的值.

How do I go about searching this array for a prefix of string, say the user types in "mount" and the array contains the word "mountain", how can I search this array and return similar values.

这是我目前的代码:

public List<Interface> returnSuggestedList(String prefix) {
    String tempPrefix = prefix;
    suggestedPhrases.clear();
    //suggestedPhrases = new ArrayList<Interface>();
    //Vector<String> list = new Vector<String>();
    //List<Interface> interfaceList = new ArrayList<Interface>();
    Collections.sort(wordsList);
    System.out.println("Sorted Vector contains : " + wordsList);
    int i = 0;
    while (i != wordsList.size()) {
        int index = Collections.binarySearch(wordsList, prefix);
        String tempArrayString = wordsList.get(index).toString();
        if (tempArrayString.toLowerCase().startsWith(prefix.toLowerCase())) {
            ItemInterface itemInt = new Item(tempArrayString);
            suggestedPhrases.add(itemInt);
            System.out.println(suggestedPhrases.get(i).toString());
            System.out.println("Element found at : " + index);
        }
        i++;
    }
    return suggestedPhrases;
}

推荐答案

如果 wordList 是固定的(不会从一个方法调用更改为另一个),您应该将其排序到其他地方,因为 sort 是成本高,并以小写形式存储.

If wordList is fixed (does not change from one method call to the other) you should sort it somewhere else, because sort is costly, and store it in lowercase.

在方法的其余部分中,您将执行以下操作:

In the rest of the method you would do something like:

List<String> selected = new ArrayList<String>();

for(String w:wordList){
    if(w.startsWith(prefix.toLower())) // or .contains(), depending on 
        selected.add(w);     // what you want exactly 
}

return selected;

这篇关于如何在数组中搜索字符串的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆