Search code examples
javastringindexoutofbounds

Java String index out of range : -1


lang.StringIndexOutOfBoundsException for the following code. The program checks for sentences without spaces to extract words which matches the dictionary of valid English words

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class WordCheckUtil{

boolean dictionaryContains(String word)
{
    List<String> dictionary = new ArrayList<String>(Arrays.asList("mobile","samsung","sam","sung",
                            "man","mango", "icecream","and",
                            "go","i","love","ice","cream"));

        if(dictionary.contains(word))
            return true;

    return false;
}

void wordCheck(String str){
    wordBreakCheck(str,str.length(),"");
}

void wordBreakCheck(String str, int length, String result){
    System.out.println(str+" "+length+" "+result);
    for (int i = 1; i <= length; i++) {
        String prefix = str.substring(0, i);
        System.out.println(prefix);
        if(dictionaryContains(prefix)){

            if(i == length){
                result += prefix;
                System.out.println("--> "+result);
                return;
            }
            System.out.println(i+" -- "+length);
            String subStr = str.substring(i,length-i);
            wordBreakCheck(subStr,length-i,result+prefix+" ");
        }
    }
}

public static void main(String[] args) {
    WordCheckUtil wr = new WordCheckUtil();
    wr.wordCheck("iloveice");
}

}

This is the error stack I am getting:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String 
index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at WordCheckUtil.wordBreakCheck(WrodCheckUtil.java:36)
    at WordCheckUtil.wordBreakCheck(WrodCheckUtil.java:37)
    at WordCheckUtil.wordCheck(WrodCheckUtil.java:20)
    at WordCheckUtil.main(WrodCheckUtil.java:44)

Solution

  • Substring takes in starting and ending indexes, not length. The line:

    str.substring(i,length-i); 
    

    is asking for a string from index i (4) to index length-i (3), not a string of the remaining length.

    Take out the -i.