How to prevent an ArrayIndexOutOfBoundsException in this case?

Tags: ,



The question is: given a string: aaaBBB

I need to print: a3B3 (counting occurrences of each letter in a given string).

I tried the following:

        String x = "aaaBBB";
        char[] c = x.toCharArray();
        StringBuilder sb = new StringBuilder();

        int count = 1;
        System.out.println(c.length);
        
        for (int i = 0; i < c.length; i++) {
                if (c[i] == c[i+1]) {
                    count++;
                } else {
                    sb.append(c[i]).append(count);
                    count = 1;
                }
        }
        System.out.println(sb);

I’m getting an ArrayIndexOutOfBounds Exception, for my last iteration, when I check c[i] with c[i+1] (pretty obvious, because the index i+1 doesn’t exist).

I’d want to know some ways to avoid getting this exception, without changing the if condition. Might sound like poor research, but I’ve been trying this for quite some time now, but not able to get through, before posting it here.

Answer

Try the following:

  • assign the first character to an independent variable.
  • when no longer equal to subsequent characters. Add to the string with that character and count.
  • then reset that character and count to the next one and 1.
  • when all characters are exhausted, add the final character and count.
String x = "aaaaBBBcDDDDD";
char[] c = x.toCharArray();
StringBuilder sb = new StringBuilder();

int count = 1;
char ch = c[0];
for (int i = 1; i < c.length; i++) {
        if (c[i] == ch) {
            count++;
        } else {
            sb.append(ch).append(count);
            ch = c[i];
            count = 1;
        }
}
sb.append(ch).append(count);
System.out.println(sb);

Prints

a4B3c1D5


Source: stackoverflow