我正在尝试计算一个字母出现在字符串 ( aabcccccaaa) 中的次数,并将它出现的次数与相应的字母一起放入一个新字符串中。问题是我得到一个StringIndexOutOfBoundsException.
我有点知道为什么,但我认为这主要是因为我的逻辑在这个问题上存在缺陷。
我在正确的轨道上吗?我做错了什么,我该如何解决?
例如,输出应该是a2b1c5a3
这是我的代码:
public class Problem {
public static void main(String []args) {
String str = "aabcccccaaa";
System.out.println(compressBad(str));
}
public static String compressBad(String str) {
int countConsecutive = 0;
String compressedString = "";
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) != str.charAt(i + 1)) {
countConsecutive++;
compressedString += "" + str.charAt(i) + countConsecutive;
countConsecutive = 0;
}
}
return compressedString;
}
}