统计字符串中不同字符出现的次数(频率)

系列文章目录

前言

《数据结构基础》c语言版 第2版,Ellis Horowitz著,朱仲涛译
2.7节,page77,习题1

一、题目描述

编写函数,读入一个字符串,统计字符串中不同字符的出现频率。

二、c++代码

1.方法1

代码如下:

#include<iostream>
#include <string.h>
#include <map>
using namespace std;

int main() {
    string str="abcaaabbabc";
    map<char,int>m;
    for(auto &i:str)
        m[i]++;
    for(auto &i:m)
        printf("%c" " " "%d\n",i.first,i.second);
    system("pause");
    return 0;
}

添加链接描述

添加链接描述

2.方法2

思路:先创建一个map,遍历字符串,逐个判断如果存在则count++,不存在则创建一个,让其value为1

代码如下:

#include<iostream>
#include <map>
using namespace std;

int main() {
    string str="abcabcacab";
    map<char,int>m;
    for(int i=0;i<str.length();i++)
    {
        map<char,int>::iterator iter = m.find(str[i]);
        if(iter!=m.end())
        {
            iter->second++;
        } else
        {
            m.insert(pair<char,int>(str[i],1));
        }
    }

    map<char,int>::iterator iter=m.begin();
    for( ;iter!=m.end();iter++)
        printf("%c" " " "%2d\n",iter->first,iter->second);

    system("pause");
    return 0;
}

map学习:
添加链接描述

2.方法3

思路:通过插入失败来增加字符的个数,如果插入失败则表明map中存在该字符,count++即可

代码如下:

#include<iostream>
#include <map>
using namespace std;

int main() {
    string str = "abcabcacab";
    map<char, int> m;
    pair<map<char, int>::iterator, bool> result;

    for (int i = 0; i < str.length(); i++) {
        result = m.insert(pair<char, int>(str[i], 1));
        if (result.second == false)
            result.first->second++;
    }
        map<char, int>::iterator iter = m.begin();
        for (; iter != m.end(); iter++)
            printf("%c" " " "%2d\n", iter->first, iter->second);

        system("pause");
        return 0;
}

总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值