Search code examples
javastringstringbuilder

Unexpected StringIndexOutOfBoundsException thrown?


I was doing a problem where I had to delete characters from a String if the adjacent characters had same value. This is my code :

import java.util.Scanner;
public class SuperReducedStringRe {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.next();
        StringBuilder s = new StringBuilder(str);
        char[] ch = str.toCharArray();

        for(int i = 0;i < str.length()-1; i++) {
            if(s.charAt(i) == s.charAt(i+1)) {
                s.delete(i,i+2);
                i=-1;
            }
        }
        System.out.print(s);
    }
}

I check and re-checked for invalid indices but couldn't find one.Can someone help me find out when and how did I go out of permissible indices?


Solution

  • The main problem is that you are operating on one variable and performing a check on another variable See:

    for(int i=0;i<str.length()-1;i++) // performing a check on str, whereas  
    

    and

    s.delete(i,i+2); // updating s(deleting the char from s)
    

    Change

    for(int i=0;i<str.length()-1;i++)
    

    to

    for(int i=0;i<s.length()-2;i++)