【C++】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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值