洛谷 P1308 统计单词数

                                 洛谷 P1308 统计单词数


题解:

  这题用上C++的库函数和string类型写的话会方便很多。并且要预处理字符串,匹配的单词和句子前后都要加空格,因为匹配的是单独的单词。最需要注意的是,用find()查找时(代码while的那部分),一定要改变查找的开始位置,也就是pos;否则会重复匹配!

  ps:不会用C++整行输入字符串的看这里

 

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6;
string word,mess;

int main(){
	int lenw,lenm,p,cnt;
	getline(cin,word);   //输入字符串 
	getline(cin,mess);
	word = ' '+word+' '; //为了匹配方便,因为单独的单词前后肯定都有一个空格 
	mess = ' '+mess+' ';
	lenw = word.length();
	lenm = mess.length();
	for(int i = 0; i < lenw; ++i)   //统一都转化成小写 
		word[i] = tolower(word[i]);
	for(int i = 0; i < lenm; ++i)
		mess[i] = tolower(mess[i]);
	if(p = mess.find(word),p == -1)  //如果一个都找不到就直接输出-1 
		cout << -1 << endl;
	else{
		int pos = p;cnt = 0;  
		while(pos != -1){            //从下一个位置开始寻找新的符合条件的单词 
			cnt++;
			pos = mess.find(word,pos+1);
		}
		cout << cnt << ' '<< p << endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值