AOJ基础题 ITP1_9_A Finding a Word

Finding a Word

  • Write a program which reads a word W and a text T, and prints the number of word W which appears in text T
  • T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive.

Input

In the first line, the word W is given. In the following lines, the text T is given separated by space characters and newlines.

“END_OF_TEXT” indicates the end of the text.

Constraints

  • The length of W ≤ 10
  • W consists of lower case letters
  • The length of T in a line ≤ 1000

Output

Print the number of W in the text.

Sample Input

computer
Nurtures computer scientists and highly-skilled computer engineers
who will create and exploit "knowledge" for the new era.
Provides an outstanding computer environment.
END_OF_TEXT

Sample Output

3

問題を解く

#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string w;
    string t;

    int count = 0;

    cin >> w;

    transform(w.begin(), w.end(), w.begin(), ::tolower);


    while (true)
    {
        cin >> t;

        if (t == "END_OF_TEXT") break;

        transform(t.begin(), t.end(), t.begin(), ::tolower);

        if (w == t) {
            count++;
        }

    }
    cout << count << endl;


    return 0;
}

A Good Try

  • 这里我一开始想得太复杂,即替换掉所有需要查找的单词,通过length相减一步得出结果,但是忽略了单词前后空格的问题,试图解决但有些顾此失彼了。
  • 对string类不够清楚,cin输入可以空格作为分隔,留坑!
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string& replace_all(string& str, const string& old_value, const string& new_value)
{
    while (true)
    {
        string::size_type pos(0);

        if ((pos = str.find(old_value)) != string::npos)
            str.replace(pos, old_value.length(), new_value);
        else break;
    }
    return str;
}

int main()
{
    string w;
    string t;
    string b(" ");
    string temp;

    int count = 0;

    getline(cin, w);

    temp = b + w;
    w = temp + b;

    transform(w.begin(), w.end(), w.begin(), ::tolower);

    while (true)
    {
        getline(cin, t);

        if (t == "END_OF_TEXT") break;

        transform(t.begin(), t.end(), t.begin(), ::tolower);

        count += (t.length() - replace_all(t, w, "").length()) / w.length();

    }
    cout << count << endl;


    return 0;
}