【问题标题】:Adding certain substring prefixes to an arraylist将某些子字符串前缀添加到数组列表
【发布时间】:2013-11-03 12:00:37
【问题描述】:

我正在尝试使用此方法根据前缀子字符串将数组值添加到 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;
}

谢谢!

【问题讨论】:

  • 你的情况正好相反。应该是length &lt; words.get(index).length()

标签: java arrays string arraylist substring


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2022-08-07
      相关资源
      最近更新 更多