2013-10-24 270 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)); 
    } 
} 
相關問題