查找字符串的所有子字符串 - StringIndexOutOfBoundsException

naz*_*art 2 java algorithm substring indexoutofboundsexception

我创建了类Word.Word有一个构造函数,它接受一个字符串参数和一个方法getSubstrings,它返回一个包含word的所有子字符串的String,按长度排序.

例如,如果用户提供输入"rum",则该方法返回一个字符串,其打印方式如下:

r
u
m
ru
um
rum 
Run Code Online (Sandbox Code Playgroud)

我想连接一个String中的子串,用换行符分隔它们("\n").然后返回字符串.

码:

    public class Word {
    String word;

    public Word(String word) {
        this.word = word;
    }
    /**
     * Gets all the substrings of this Word.
     * @return all substrings of this Word separated by newline
     */

    public String getSubstrings()
    {
        String str = "";
        int i, j;
        for (i = 0; i < word.length(); i++) {
            for (j = 0; j < word.length(); j++) {
                str = word.substring(i, i + j);
                str += "\n";
            }
        }
        return str;
    }
Run Code Online (Sandbox Code Playgroud)

但它抛出了异常:

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1911)
Run Code Online (Sandbox Code Playgroud)

我坚持到这一点.也许,你有这个方法签名的其他建议public String getSubstrings().
如何解决这个问题?

rit*_*esh 6

例外情况分析:

来自Java7 Docs的StringIndexOutOfBoundsException

public class StringIndexOutOfBoundsException extends IndexOutOfBoundsException
Run Code Online (Sandbox Code Playgroud)

由String方法抛出,以指示索引是负数还是大于字符串的大小.

来自Java 7 Docs of substring

public String substring(int beginIndex,int endIndex)
Run Code Online (Sandbox Code Playgroud)

返回一个新字符串,该字符串是此字符串的子字符串.子字符串从指定的beginIndex开始,并扩展到索引endIndex - 1处的字符.因此子字符串的长度为endIndex-beginIndex.

我想这样的: 子字符串的长度为endIndex的-的beginIndex进入String index out of range: -1.我已经对多个案例进行了测试,认为我的假设是正确的,但感谢任何其

对于-1: "rum".substring(2,1);会给你String index out of range: -1

Parameters:
    beginIndex - the beginning index, inclusive.
    endIndex - the ending index, exclusive.
Run Code Online (Sandbox Code Playgroud)

StringIndexOutOfBoundsException的原因:

在给定的代码片段中,substring尝试获取的字符串endIndex超过String的总长度(i+j将超过字符串的总长度):

str = word.substring(i, i + j);
Run Code Online (Sandbox Code Playgroud)

考虑i = 2且j = 2的情况,对于单词"rum"

然后str=word.substring(2, 4); 是不可能的

类似于问题中给出的代码片段的解决方案:

这应该解决问题:

 public String getSubstrings()
    {
        String str="",substr = "";
        for (int i = 0; i < word.length(); i++) {
            for (int j = 0; i+j <= word.length(); j++) { //added i+j and equal to comparison
               substr = word.substring(j, i + j); //changed word.substring(i, i + j) to word.substring(j, i + j)
               if("".equals(substr))continue; //removing empty substrings
               str += substr; //added concatenation + operation
               str += "\n";
            }
        }
        return str+word;
    }
Run Code Online (Sandbox Code Playgroud)

测试用例:

因为word="rum",这将给出输出:

r
u
m
ru
um
rum
Run Code Online (Sandbox Code Playgroud)

  • 这是因为`str`在`=`的内部循环中被覆盖.把它改成`+ =` (2认同)