/**
bit_2009_4
2018-8-14 10:35
4. 输入一个英文句子,把句子中的单词按出现次数按从多到少把单词和次数在屏幕上输出来,
要求能识别英文句号和逗号,即是说暂不要求识别其他符号
**/
#include<iostream>
#include<vector>
#include<string.h>
#include<algorithm>
#include<memory.h>
using namespace std;
struct Word{
int count;
char w[20];
};
Word getword(char sentence[],int low,int high){
Word w;
for(int f=0;f<20;f++){ //不是很懂为什么每次重新定义后必须要初始化,否则上次的数据会有残留~
w.w[f]='\0';
}
for(int j=low,k=0;j<=high;j++,k++){
w.w[k]=sentence[j];
w.count=1;
}
return w;
}
bool cmp(Word a, Word b){
if(a.count>b.count) return 1;
else return 0;
}
int main(){
vector<Word> word;
Word w;
char sentence[100000];
cout<<"请输入句子:"<<endl;
gets(sentence);
int low=0,high;
int flag=0;
for(int i=0;i<strlen(sentence);i++){
while(sentence[i]!=','&&sentence[i]!='.'&&sentence[i]!=' ') i++;
high=i-1;
w=getword(sentence,low,high);
w.count=1;
if(word.size()==0){
word.push_back(w);
}
else{
flag=0;
for(int j=0;j<word.size();j++){
if(strcmp(word[j].w,w.w)==0){
word[j].count++;
flag=1;
break;
}
}
if(flag==0){
word.push_back(w);
}
}
low=i+1;
}
sort(word.begin(),word.end(),cmp);
cout<<"输出:"<<endl;
for(int i=0;i<word.size();i++){
cout<<word[i].w<<" "<<word[i].count<<endl;
}
return 0;
}