记录PTA甲级以及C++部分语法知识1071**-字符串处理

一开始我是想逐个查找单词,每次用string.find()方法,一边计数一边删除,直到原串为空,但是最后发现一个异常致命的错误,find并不是全词匹配,假如说识别出一个单词a,那么后面所有单词中的a就都被删除了。。。

最后还是得用map,一边识别单词,识别出一个就统计一个,而不是向后查找。但是还是会错一个。

推荐一版:https://blog.csdn.net/hy971216/article/details/81563094

#include<iostream>
#include<string>
#include<map>
using namespace std;


map<string,int> words;
map<string,int>::iterator it;

bool Isc( char c){
	if(c>='a'&&c<='z'|| c>='0'&&c<='9')
		return true;
	return false;
}



int main(){
	string s,word;
	getline(cin,s);
	int len=s.length(),i=0;
	int st=0,l;
	while(i<len){
		if(s[i]>='A'&&s[i]<='Z')
                s[i]=s[i]+32;
		if(!Isc(s[i])){
			i++;
			continue;
		}
		st=i;
		l=0;
		while(Isc(s[i])){
			i+=1;
			l+=1;
		}
		word=s.substr(st,l);
		//cout<<"word:"<<word<<"|| st:"<<st<<" l:"<<l<<" i:"<<i<<endl;
		i+=1;
		if(words.find(word)==words.end())
			words[word]=1;
		else
			words[word]+=1;
	}

	
	int t=1;
	for(it=words.begin();it!=words.end();it++){
		if(it->second>t){
			word=it->first;
			t=it->second;
		}
		else if(it->second==t && it->first<word)
		{
			word=it->first;
			t=it->second;
		}
	}
	cout<<word<<" "<<words[word];

	system("pause");
	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值