//输出字符串各个字符的个数
#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容器.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;
}
上面的代码只适合有两个重复的字符,下一篇将对此优化。