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.
Try the following:
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