2013-10-24 272 views
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; 
} 

谢谢!

+3

您的病情逆转。应该是'length

回答

0

谢谢Rohit! 你确实是对的! 发生变化:

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

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

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

1

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

for(int index = 0; index < words.size(); index++) 
{ 
    if(words.get(index).startsWith(prefix)) 
      prefixCheck.add(words.get(index)); 
    } 
} 
相关问题