Java 字符串压缩到字符数组列表

Java 字符串压缩到字符数组列表,java,Java,我有一个字符串,我正在压缩为一个带有计数的字符数组。我没有得到字符串中最后一个字符的计数 public class StringComp { public static void main(String[] args) { String st = "aaabbccaaaaadddd"; ArrayList<Character> chars = new ArrayList<>(); int count = 1;

我有一个字符串,我正在压缩为一个带有计数的字符数组。我没有得到字符串中最后一个字符的计数

public class StringComp {

    public static void main(String[] args) {

        String st = "aaabbccaaaaadddd";
        ArrayList<Character> chars = new ArrayList<>();
        int count = 1;
        char ct;

        for(int i = 0; i < st.length() - 1; i++) {
            if(st.charAt(i) == st.charAt(i+1)) {
                count++;
            }else {
                ct = Integer.toString(count).charAt(0);
                chars.add(ct);
                chars.add(st.charAt(i));
                count = 1;  
            }
        }
        System.out.println(chars.toString());

    }

}
我的输出应该是:

[3, a, 2, b, 2, c, 5, a, 4, d]

我似乎在代码中找不到bug。

您应该在循环后添加最终计数:

...
for(int i = 0; i < st.length() - 1; i++) {
    if(st.charAt(i) == st.charAt(i+1)) {
        count++;
    }else {
        ct = Integer.toString(count).charAt(0);
        chars.add(ct);
        chars.add(st.charAt(i));
        count = 1;  
    }
}
ct = Integer.toString(count).charAt(0);
chars.add(ct);
chars.add(st.charAt(st.length()-1));
。。。
对于(int i=0;i

还请注意,将计数存储为单个
字符是个坏主意。如果计数大于9怎么办?

Eran是的,你是对的。谢谢你!!
...
for(int i = 0; i < st.length() - 1; i++) {
    if(st.charAt(i) == st.charAt(i+1)) {
        count++;
    }else {
        ct = Integer.toString(count).charAt(0);
        chars.add(ct);
        chars.add(st.charAt(i));
        count = 1;  
    }
}
ct = Integer.toString(count).charAt(0);
chars.add(ct);
chars.add(st.charAt(st.length()-1));