《面试准备》c++找出字符串中各个字符出现的次数

题目描述:

输入:一个字符串

输出:每个字符出现的个数

举例:

输入:

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;
}

测试:

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值