0

我正在尝试使用此方法根据前缀子字符串将数组值添加到 prefixCheck,但是当我的前缀长于条目本身时,我会不断收到错误消息。我如何为此使用支票?

/**
 * This method returns a list of all words from the dictionary that start with the given prefix.
 *
 */
public ArrayList<String> wordsStartingWith(String prefix)
{
    ArrayList<String> prefixCheck = new ArrayList<String>();
    int length = prefix.length();
    for(int index = 0; index < words.size(); index++)
    {
        if(length > words.get(index).length())
        {
            if(words.get(index).substring(0, length).equalsIgnoreCase(prefix))
            {
                prefixCheck.add(words.get(index));
            }
        }
    }
    return prefixCheck;
}

谢谢!

4

2 回答 2

1

您也可以尝试使用 String.startsWith(String)。

for(int index = 0; index < words.size(); index++)
{
    if(words.get(index).startsWith(prefix))
            prefixCheck.add(words.get(index));
    }
}
于 2013-10-24T16:53:51.390 回答
0

谢谢罗希特!你确实是对的!改变:

if(length > words.get(index).length())

if(length < words.get(index).length())

完全解决了我的字符串索引超出范围错误。

于 2013-10-24T16:45:48.853 回答