java统计字符串连续重复的数量
以下是一个示例代码,它可以计算一个字符串中连续重复的字符的数量:
public class StringRepeatCount {
public static void main(String[] args) {
String str = "aaabbbbccccccdddddd";
int count = 1;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
count++;
} else {
System.out.println(str.charAt(i - 1) + "连续重复了" + count + "次");
count = 1;
}
}
System.out.println(str.charAt(str.length() - 1) + "连续重复了" + count + "次");
}
}
这个程序会遍历字符串,找到连续重复的字符并计数,然后输出结果。在上述示例中,输出将为:
a连续重复了3次
b连续重复了4次
c连续重复了6次
d连续重复了6次
注意,在最后一个字符之后,我们需要再次输出计数值。
原文地址: https://www.cveoy.top/t/topic/bhr7 著作权归作者所有。请勿转载和采集!