已知字符串为:"aaabbbbbbcadd"
思路1:
1.创建一个map key:出现的字符 value:出现的次数
2.获取字符串中的每一个字符
3.查看字符是否在Map中作为key存在.若存在:说明已经统计过 value+1 不存在:value=1
代码如下:
-
public class CountString {
-
public static void main(String[] args) {
-
String str = "
aaabbbbbbcadd";
-
Map<Character,Integer> map = new HashMap<Character,Integer>();
-
for(int i=0;i<str.length();i++){
-
char c = str.charAt(i);//用toCharArray()也可以
-
if(map.containsKey(c)){//若统计过
-
map.put(c, map.get(c)+1);
-
}else{
-
map.put(c, 1);
-
}
-
}
-
System.out.println(map);
-
}
-
}
思路2:
#include <iostream>
int main(int argc, const char * argv[]) {
int count[256] = {0};
char str[] = "I am a student!";
for (int i = 0; str[i] != '\0'; i++)
count[str[i]]++;
for (int i = 0; i < 256; i++) {
if (count[i] > 0)
printf("字符 %c 出现了 %d 次\n", i, count[i]);
}
return 0;
}