Evangeline Slape
Evangeline Slape

Reputation: 15

SubString error indexoutofbounds Java

I've decided to write my own subString method, however when I test it within my test driver I receive an error with one of my lines in my SubString method. This is the error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(Unknown Source)
at unisa.util.StringImproved.subString(StringImproved.java:618)

This is my code for my subString:

    public String subString(int start, int end) {
    //empty string to append the new string's characters to
    String subString = "";
    //creating a new string to store content to allow function
    String s1 = new String(content);
    //read each character in the string and append based on the index
    for (int i=start; i<=end; i++){
        subString += s1.charAt(i);
    }
    //convert string back to a char array
    content = subString.toCharArray();
    return subString;

}

The error is picking up the line subString += s1.charAt(i); Anyone able to shed some light on what i'm doing wrong??

PS. this isn't for an assignment just a bit of boredom and wanting to re-create the java functions myself.

Thanks in advance!!

I have added my testing methods as per request!!

private int testSubString(String testID) {
    int errorCount=0;



    header(testID);

    {
        System.out.println("Test[getting substring from middle] ");
        StringImproved str = new StringImproved("0123456789");
        String result = str.subString(1,2);
        errorCount+=handleResult(result,"1")?0:1;
    }

    {
        System.out.println("Test[getting first characters] ");
        StringImproved str = new StringImproved("0123456789");
        String result = str.subString(0,2);
        errorCount+=handleResult(result,"01")?0:1;
    }

    {
        System.out.println("Test[getting last characters] ");
        StringImproved str = new StringImproved("0123456789");
        String result = str.subString(str.length()-3,str.length());
        errorCount+=handleResult(result,"789")?0:1;
    }


    {
        System.out.println("Test[out of range] ");
        StringImproved str = new StringImproved("0123456789");
        String result = str.subString(0,str.length()+1);
        errorCount+=handleResult(result,null)?0:1;
    }

    {
        System.out.println("Test[zero length source] ");
        StringImproved str = new StringImproved("");
        String result = str.subString(0,str.length()-1);
        errorCount+=handleResult(result,null)?0:1;
    }
    return errorCount;      
}

Upvotes: 0

Views: 1343

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Change

for (int i = start; i <= end; i++){
   subString += s1.charAt(i);
}

to

for (int i = start; i < end; i++){
    subString += s1.charAt(i);
}

But this would be error prone, because it depends how do you invoke your own substring() method. The reason is that the parameters may exceed the length of the string (or be negative, for example).

A better approach is to make a couple of checks to ensure the parameters are valid.

if (start >= 0 && end >= start) {
   end = Math.min(myString.length(), end);
} else { 
   throw new IllegalArgumentException("Invalid arguments");
}

and the do the loops.

You should also note, that the String#chatAt(int i) method returns the character of the zero-based char[] array that represents the String object.

Upvotes: 2

Maroun
Maroun

Reputation: 95968

Arrays are zero-based.

If your string is of length N, the indexes are from 0 to N - 1 (Total length of N).

Your for loop should be:

                   ↓‎
for (int i=start; i<end; i++) {

Example:

"This is a test" is of size 14, T is on the 0 place, the last t is the 13 place.


As @sanbhat mentioned, you need to check some cases, for example, what will happen it the size of content is smaller than end?

Upvotes: 5

Related Questions