概述
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;
}
最后
以上就是动听柜子为你收集整理的【C++】AOJ基础题 ITP1_9_A Finding a Word的全部内容,希望文章能够帮你解决【C++】AOJ基础题 ITP1_9_A Finding a Word所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复