请帮帮我,我想transfrom字符串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);
}
}
Run Code Online (Sandbox Code Playgroud)
但输出是,
2AB2SD
Run Code Online (Sandbox Code Playgroud)
这个结果并不像我想要的那样.
请帮我转换"AABSSSD"到"2AB3SD".
在你的else部分,你应该设置1反而不是0因为新角色第一次出现,
else {
newStr.append(count);
newStr.append(temp);
count = 1;//Just change this
}
Run Code Online (Sandbox Code Playgroud)
并替换1而不是0来自 ,String x = x.replace("1", "");因为在 中出现过一次0A看起来无效,所以它应该代替。AString1A0A
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |