输入一个字符串,输出这个字符串中重复的元素及其个数

//输出字符串各个字符的个数
#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;
}

上面的代码只适合有两个重复的字符,下一篇将对此优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值