0

我正在尝试计算一个字母出现在字符串 ( 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;
  }
}
4

2 回答 2

5

当是最后一个索引时,此行将str.charAt(i + 1)读取超出范围,现在超出范围。ii+1

于 2019-02-07T15:33:01.587 回答
0

对于它的价值,这就是我要做的:

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();
}
于 2019-02-07T16:30:37.320 回答