我正在尝试计算一个字母在字符串(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;
}
}
当
i
是最后一个索引时,此行str.charAt(i + 1)
将读取出界外,i+1
现在越界。
对于它的价值,这是我会做的:
public static String compressBad(final String str) {
if (str == null || str.length() < 0) {
return "";
}
int countConsecutive = 0;
StringBuilder sb = new StringBuilder();
char previousLetter = str.charAt(0);
for (char c : str.toCharArray()) {
if (c == previousLetter) {
countConsecutive++;
} else {
sb.append(previousLetter).append(countConsecutive);
previousLetter = c;
countConsecutive = 1;
}
}
sb.append(previousLetter).append(countConsecutive);
return sb.toString();
}