Java 如何转换字符串";AABSSSD“;变成;2AB3SD“什么;?

Java 如何转换字符串";AABSSSD“;变成;2AB3SD“什么;?,java,string,Java,String,我想将字符串AABSSSD转换为2AB3SD(有人称之为加密)。 这就是我试图解决它的方式: public class TransformString { public static void main(String[] args) { String str = "AABSSSD"; StringBuilder newStr = new StringBuilder(""); char temp = str.charAt(0);

我想将字符串
AABSSSD
转换为
2AB3SD
(有人称之为加密)。 这就是我试图解决它的方式:

public class TransformString {

    public static void main(String[] args) {
        String str = "AABSSSD";
        StringBuilder newStr = new StringBuilder("");
        char temp = str.charAt(0);
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (temp == str.charAt(i)) {
                count++;
            } else {
                newStr.append(count);
                newStr.append(temp);
                count = 0;
            }
            temp = str.charAt(i);
            if(i == (str.length() - 1)){
                newStr.append(str.charAt(i));
            }
        }
        String x = String.valueOf(newStr);
        x = x.replace("0", "");
        System.out.print(x);
    }
}
这个结果并不是我想要的


请帮助我将
“AABSSSD”
转换为
“2AB3SD”

中,否则
部分应将计数器设置为
1
,而不是
0
,因为新字符第一次出现

else {
    newStr.append(count);
    newStr.append(temp);
    count = 1;//Just change this
}

并从
字符串中替换
1
,而不是
0
因为
0A
看起来无效,因为
A
字符串中出现过一次,所以它应该是
1A
而不是
0A

您的
否则
部分是错误的。 请将其编辑为:

newStr.append(count);
newStr.append(temp);
count = 1;
而不是:

newStr.append(count);
newStr.append(temp);
count = 0;

来点Java 8怎么样?:-)

newStr.append(count);
newStr.append(temp);
count = 0;
String str = "AABSSSD";
String x = Arrays.stream(str.split(""))
    .collect(Collectors.groupingBy(Function.identity())).values().stream()
    .map(l -> (l.size() > 1 ? l.size() : "") + l.get(0))
    .collect(Collectors.joining());
System.out.println(x);