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

已知字符串为:"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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值