统计字符串中字符的出现的频率,最好C++语言。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了统计字符串中字符的出现的频率,最好C++语言。相关的知识,希望对你有一定的参考价值。

比如a,b,c,d,d,w,q,e,r,e,i,e。求出最高频率e,然后是d,然后是其他。

#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <algorithm>

using namespace std;

int cmp(const pair<char,int> &x, const pair<char,int> &y)

return x.second > y.second;


int main(void)

char a[20] = 'a','b','c','d','e','a','c','s','g','e','b','b','b','a','c','c';
int i = 0,j;
map<char,int> word_count;
vector<pair<char,int> > vp;

while(a[i] != '\\0')

++word_count[a[i]];
++i;


map<char,int>::iterator iter;



for(iter = word_count.begin(); iter != word_count.end(); iter++)

vp.push_back(make_pair(iter->first,iter->second));


sort(vp.begin(), vp.end(), cmp);

vector<pair<char,int> >::iterator iter1;
for(iter1 = vp.begin(); iter1 != vp.end(); iter1++)

cout<<iter1->first<<'\\t'<<iter1->second<<endl;

 vector是用来排序的,按value排序。vector中第一个元素为频率最高,最后一个为频率最低。

参考技术A 可以用Map,map的value表示频率,然后根据频率排序就可以了

字符串字符统计

描述: 统计字符串中每个字符的出现频率,返回一个 Object,key 为统计字符,value 为出现频率

1. 不限制 key 的顺序
2. 输入的字符串参数不会为空
3. 忽略空白字符

示例1

输入:\'hello world\'

输出:{h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1}

以上是关于统计字符串中字符的出现的频率,最好C++语言。的主要内容,如果未能解决你的问题,请参考以下文章

词频统计

c++ 文本文件中查找字符串

统计一个字符串中第一次出现且频率最高的字符

第三次作业

C++ 输入一行字符,分别统计出其中英文字母个数~~

统计字符出现频率(java)