计算一个字符串中每个字符出现的次数

已知字符串为:"aaabbbbbbcadd"

思路1:

1.创建一个map    key:出现的字符  value:出现的次数
 2.获取字符串中的每一个字符
 3.查看字符是否在Map中作为key存在.若存在:说明已经统计过  value+1  不存在:value=1

代码如下:

  1. public class CountString {

  2. public static void main(String[] args) {

  3. String str = "aaabbbbbbcadd";

  4. Map<Character,Integer> map = new HashMap<Character,Integer>();

  5. for(int i=0;i<str.length();i++){

  6. char c = str.charAt(i);//用toCharArray()也可以

  7. if(map.containsKey(c)){//若统计过

  8. map.put(c, map.get(c)+1);

  9. }else{

  10. map.put(c, 1);

  11. }

  12. }

  13. System.out.println(map);

  14. }

  15. }

思路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;

}

猜你喜欢

转载自blog.csdn.net/github_34457546/article/details/81456972