我正在尝试查找字符串中的字符数并打印出来。
例如:
输入:
aaaaaggff
输出:(不成功)
aaaaa5gg2ff2
代码:
for (int h = 0; h < fe - 1; h++) {
if (s4[h] == s4[h + 1]) {
++c;
sw[h] = s4[h];
}
else {
String st = Character.toString(s4[h]);
st = st + "" + c;
if (sw[h] == ' ') {
sw[h] = st.charAt(0);
sw[h + 1] = st.charAt(1);
c = 1;
st = "";
}
else {
int v = h * 2 - 1;
sw[v] = st.charAt(0);
sw[v + 1] = st.charAt(1);
c = 1;
st = "";
}
}
}
答案 0 :(得分:0)
这里的假设是您要在字符更改之前打印重复的数字。
您可以尝试:
public class MyClass {
public static void main(String args[]) {
String input = "aaaaaggff";
char c = input.charAt(0);
int count = 1;
System.out.print(c);
for (int i = 1; i < input.length(); i++) {
if (input.charAt(i) == c) {
System.out.print(input.charAt(i));
count++;
} else {
System.out.print(count);
System.out.print(input.charAt(i));
count = 1;
c = input.charAt(i);
}
}
// Print the count of the final character
System.out.println(count);
}
}
结果
aaaaa5gg2ff2