题目描述:
输入:一个字符串
输出:每个字符出现的个数
举例:
输入:
asdaassd
输出:
a:3
s:3
d:2
这里用c++ STL标准模板库中的map可以轻松实现:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <map>
using namespace std;
int main(void){
map<char,int> ms;
map<char,int>::iterator p,mEnd;
string s;
cin>>s;
int len = s.length();
for(int i=0;i<len;i++){
p=ms.find(s[i]); //find key
if(p!=ms.end()){ //找到已有的key,value自加
p->second++;
}
else{ //反之没找到就插入新的key,value为1
ms.insert(pair<char,int>(s[i],1));
}
}
//输出结果
p=ms.begin();
mEnd=ms.end();
for(;p!=mEnd;p++){
cout<<p->first<<":"<<p->second<<endl;
}
return 0;
}
其实,用c++ STL标准模板库中的vctor也可以轻松实现,只是稍微麻烦一点:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
char cha;
struct str{
char ch;
int sum;
};
bool findx(const str &s){
return s.ch == cha;
}
int main(void){
vector<str> ms;
vector<str>::iterator p,mEnd;
string s;
str sttr;
cin>>s;
int len = s.length();
for(int i=0;i<len;i++){
cha = s[i];
p=find_if(ms.begin(),ms.end(),findx);
if(p!=ms.end()){ //find
p->sum++;
}
else{ //not find
sttr.ch = cha;
sttr.sum = 1;
ms.push_back(sttr);
}
}
//print
p=ms.begin();
mEnd=ms.end();
for(;p!=mEnd;p++){
cout<<p->ch<<":"<<p->sum<<endl;
}
return 0;
}
测试:

题目延伸:
现在,找出一系列字符串中各个字符串出现的次数
思路:只需加一个vector来存储字符串
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <map>
using namespace std;
int main(void){
vector<string>vs;
map<string,int> ms;
map<string,int>::iterator p,mEnd;
int n;
string s;
cin>>n;
for(int i=0;i<n;i++){
cin>>s;
vs.push_back(s);
}
for(int i=0;i<vs.size();i++){
p=ms.find(vs[i]);
if(p!=ms.end()){
p->second++;
}
else{
ms.insert(pair<string,int>(vs[i],1));
}
}
p=ms.begin();
mEnd=ms.end();
for(;p!=mEnd;p++){
cout<<p->first<<":"<<p->second<<endl;
}
return 0;
}
测试:

本文介绍使用C++ STL中的map和vector实现统计字符串中每个字符出现次数的方法,包括单字符串和多字符串的场景。
1603

被折叠的 条评论
为什么被折叠?



