Given a string composed of numbers such as: "1239586838923173478943890234092"; count the number of times each number appears.
Use String common classes and for loop
String str = "1239586838923173478943890234092";
//将字符串转化为字符数组
char[] ch = str.toCharArray();
//外层循环将字符0-9与目标字符串比较
//字符'0'在字符集中是48代替,且字符可以加加操作和比较操作
for(int i = '0' ; i < '9' ; i++){
//记录相同数字的个数(每次循环需要置为0)
int count = 0;
//内层循环一次将i和字符串从头到尾比较一次
for(int j = 0; j < ch.length; j++){
if(ch[j] == i){
coun++;t
}
}
//内层循环结束后打印
System.out.println("数字"+ i +"出现的次数" + count);
}
Output result:
0 appeared 2 times
1 appeared 2 times
2 appeared 4 times
3 appeared 6 times
4 appeared 3 times
5 appeared 1 time
6 appeared 1 time
7 appeared 2 times
8 appeared 5 times