更新时间:2016-05-18 22:34:25浏览次数:1+次
//输出字符串各个字符的个数
#include "iostream"
#include "windows.h"
#include "string"
#include "map"
using namespace std;
int main()
{
string str;
int len;
char word;
cin>>str;
int index;
map<char,int> counts;
len=str.length();
int i;
for(i=0; i<len; i++)
{
word=str.at(i);
++counts[word];//将输入的字符串中的字符挨个输入到map容器
}
for(i=0; i<len; i++)
{
char cha=str.at(i);
map<char,int>::iterator num(counts.find(cha));//开始统计技术
if(num==counts.end())
{
cout<<"查找出错!!!"<<endl;
}
if(num->second>1)//判断是否重复
{
index=str.find(cha,i+1);
if(index!=str.npos&&i+1<len)
{
cout<<num->first<<" ";
cout<<num->second<<endl;
}
}
}
system("pause");
return 0;
}
在构造map时,传入char为数据,int为数量。这就为我们统计字符提供了方便。不过上面的代码只适合字符串中有两个重复字符的情况,若是大于两个,那么在输出的时候,就会重复了。后续改进算法......相关资讯