Find all substrings of a string - StringIndexOutOfBoundsException

Posted by nazar_art on Stack Overflow See other posts from Stack Overflow or by nazar_art
Published on 2013-07-03T16:34:06Z Indexed on 2013/07/03 17:05 UTC
Read the original article Hit count: 388

I created class Word. Word has a constructor that takes a string argument and one method getSubstrings which returns a String containing all substring of word, sorted by length.

For example, if the user provides the input "rum", the method returns a string that will print like this:

r
u
m
ru
um
rum 

I want to concatenate the substrings in a String, separating them with a newline ("\n"). Then return the string.

Code:

    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;
    }

But it throws exception:

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1911)

I stuck at this point. Maybe, you have other suggestions according this method signature public String getSubstrings().
How to solve this issue?

© Stack Overflow or respective owner

Related posts about java

Related posts about algorithm