题目:
编写程序,读入几行文本,并打印一个表格,显示每个不同单词在文本中出现的次数。
例如输入:Welcome to C++ world ! Happy birthday to you .This is the weather report across the world for tomorrow , talk about it in pairs following the model below.
结果为 Welcome 出现 1 次,to 出现 2 次,C++ 出现 1 次等。
本人比较菜,感觉上了考场,STL统统都想不起来用,所以写了一个不用STL的版本练手。只用到cstring库函数和c++的string类。
#include<iostream>
#include<cstring>
using namespace std;
void transform(char * s){
for(int i=0;s[i]!='\0';i++)
{
if(s[i]>='A'&&s[i]<='Z')s[i]+=32; //大写全部转小写
}
}
int main(){
// char ch[]="May day may Day may May good good i am happy happy";
int cnt[30]={0};
string word[30];
char ch[200];
cout<<"请输入句子:";
cin.getline(ch,200);
char* t = strtok(ch," !?.,"); //strtok函数,后一个参数是分隔符的集合,很好用
transform(t);
word[0] = t;
cnt[0] = 1;
int len = 1;
while(1){
int wordId; //单词按出现顺序,占用一个ID
t = strtok(NULL," !?.,"); //循环里面,strtok第一个参数要写NULL
if(t==NULL)break;
int flag=0; //重复标志
for(wordId=0;wordId<len;wordId++){ //跑循环,查找有没有重复单词
transform(t); //转小写
string temp = t; //因为string之间比较,可以直接等号而不用strcmp,就偷懒用string了
//另外发现char*类型可以直接给string赋值
if(temp == word[wordId]){
cnt[wordId]++; //ID对应的单词数+1
flag = 1; //重复了
break; //退出循环
}
}
if(flag==0){ //没重复
cnt[wordId]++;
word[len]=t;
len++;
}
}
for(int i=0;i<len;i++){
cout<<word[i]<<"出现了"<<cnt[i]<<"次"<<endl;
}
}
运行结果:
按自己习惯写的,其实写的不太精巧,还可以改进。