<NOIP> 18 . P1308 统计单词数

来源:互联网 发布:手机能注册淘宝邮箱吗 编辑:程序博客网 时间:2024/05/29 13:11

题解:这是洛谷的第18道题目,因为在很多文本编辑工具中都有查找的功能,也有计数的功能。所以,这方面的练习对于之后想做文本编辑器也是很有帮助的。

注意

1 . 我们在选择输入变量的类型时,应该不直接使用std::string,因为在输入的字符串中存在空格,std::string不识别空格,应该先用char作为输入,然后赋值给std::string;

2 . 字符串中,可能存在大写或者小写。因此,我们需要将大写或者小写的字符转换成统一格式;

3 . 匹配不到指定的字符串,输出-1;

源代码:

#include <iostream>#include <string.h>#include <sstream>#include <stdlib.h>using namespace std;string transform(const std::string str){    string transformstr;    char *value = new char[1];    for (size_t i = 0; i < str.size(); i++)    {        strcpy(value, str.substr(i, 1).c_str());        transformstr += toupper(*value);    }    return transformstr;}int main(){    string first, second, third = "", middle;    char c;    int sum = 0, pos;    bool firstpos = true;    cin >> first;    cin.get();    while ((c = cin.get()) != '\n')        second += c;    first = transform(first);    second = transform(second);    unsigned int stringsize = second.size();    for (size_t i = 0; i < stringsize; i++)    {        while (i<stringsize && (middle = second.substr(i, 1)) != " ")        {            third += middle;            i++;        }                        if (first == third)        {            sum++;            if (firstpos)            {                pos = i - third.size();                firstpos = false;            }        }                    third = "";    }    if (sum != 0)        cout << sum << " " << pos << endl;    else    {        sum = -1;        cout << sum << endl;    }    system("pause");    return 0;}