public class StringDemo {
public static void main(String[] args){
String str = "aaaabbbbccccdddda";
//分别为四个字母定义计数器;
int count1 = 0;int count2 = 0;
int count3 = 0;
int count4 = 0;
char[] c = str.toCharArray(); //将字符串转换成字符数组;
for(int i =0;i<c.length;i++){
if(c[i]=='a'){
count1++;
}else if(c[i]=='b'){
count2++;
}else if(c[i]=='c'){
count3++;
}else if(c[i]=='d'){
count4++;
}
}
System.out.println("a"+count1+"b"+count2+"c"+count3+"d"+count4);
}
}
本文介绍如何使用Java对字符串中的字符进行计数并遍历。通过将字符串转换为字符数组,然后逐个检查每个字符来实现计数功能。
1万+

被折叠的 条评论
为什么被折叠?



