0

I'm writing a method for deleting dups from a String using StringBuffer. The method is returning StringIndexOutOfBoundsException. How can I fix it ?

public static void removeDups( String myString ){

        StringBuffer sb = new StringBuffer( myString );
        int len =  myString.length(); 

        for ( int j = 0; j < len; j++ ){

            char c = sb.charAt(j);

            for ( int k = len - 1 ; k > j ; k-- ){

                if ( sb.charAt(k) == c ){

                    sb.deleteCharAt(k);
                    len--; 
                }

            }
        }

        System.out.println("After deleting the dups : " + sb.toString() ); 
    } 
2
  • 1
    Did you try debugging? Commented Aug 3, 2015 at 19:09
  • Technically, it isn't returning StringIndexOutOfBoundsException it is throwing it. For future references. Commented Aug 3, 2015 at 19:27

1 Answer 1

3
for (int k = len - 1 ; k > j ; k++ )

If you're trying to iterate downwards, it needs to be k--, not k++. Right now, the second iteration is going to have k = len, and that's out of bounds. You're updating upwards infinitely instead of down to a bound.

You're also missing a bracket: it needs to be

 if ( sb.charAt(k) == c ) {
    sb.deleteCharAt(k);
    len--; 
 }

(While we're at it, there is essentially no reason ever to use StringBuffer instead of StringBuilder, which provides ~the same API without synchronization overhead.)

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, that's correct. I changed it, but, still the method deletes one repetition. Say, when I put "njznj" it will print "njzj".
Thanks for mentioning about the bracket. I also write some Python and thought it will cover two lines without the bracket. Now, the program is fine and thanks for your effort.
and "while we're at it", deleting characters (or short substrings) from StringBuilder repeatedly is almost always a lot slower than copying the parts that should remain, as delete will have to move all the text after the deletion point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.