PAT 1027Speech Patterns (25)

来源:互联网 发布:腾讯云域名dns是多少 编辑:程序博客网 时间:2024/05/29 18:09

思路

  • 1.分词,用char[]储存输入数据,gets(a)输入一行数据,s=s+a(i)//(string 的性质)划分并组合成单词。
  • 2.统计,用map<string,int>统计数据即可。

自己出错的地方

  • 1.char a[]是用gets(a)输入,不是cin>>a,是用strlen(a)统计长度不是用sizeof(a)
  • 2.用isalnum判断是否为字母或者数字,tolower将大写变为小写。
  • 3.mp[s]初始值为0。
  • 4.map<string, int>::iterator it;可以用it->second或者it->first找出值。

代码

#include <stdio.h>#include<iostream>#include <map>#include <ctype.h>#include <string>#include <string.h>#include <sstream>using namespace std;map<string, int> mp;char a[1048576];int main(){    //错了cin >> a;    gets_s(a);    //int l = sizeof(a);    int l = strlen(a);    string s;    int i = 0;    while (i<l)    {        //分词        //isalnum判断字符变量c是否为字母或数字,若是则返回非零,否则返回零        while (!isalnum(a[i]) && i<l)        {            i++;        }        s = "";        while (isalnum(a[i])&&i<l)        {            //tolower功 能: 把字符转换成小写字母,非字母字符不做出处理 头文件:在VC6.0可以是ctype.h或者stdlib.h,常用ctype.h            s += tolower(a[i]);            i++;        }        //统计,mp[s]初始值为0        mp[s]++;    }    int max = -1;    string out;    map<string, int>::iterator it;    it = mp.begin();    for (; it != mp.end(); it++)    {        //it->sencond 不会用        if (it->second>max)        {            max = it->second;            out = it->first;        }    }    cout << out <<" "<< max << endl;    //cout << l << endl;    return 0;}
0 0
原创粉丝点击