跳到正文

个人记录

[NOIP2011 普及组]统计单词数 题解

Monkey_约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
获赞
1

版本

  1. v1当前

这是一道历年真题,这题的做法太多了,但看了看大家的解法,都有些复杂,下面本蒟蒻来献做法:

string 中的 find 函数(20几行)

先来介绍一下我的思路吧~

  • 1 . 用 getline(cin , 数组名) 输入。

  • 2 . 先全部转小写(利用 toltwer()toltwer() 函数转),如样例一:ToTo —> toto。

  • 3.加空格 , 以便搜索,如样例一: (空格) toto (空格)(空格) bebe (空格)(空格) oror (空格) ……

  • 4.开始寻找(分两种情况)

1 . 先判特例,找不到的情况,输出 −1-1。

2 . 如果找到了,那就计数 +1

  • 5.输出

接下来就是分步实现:

1. 输入

输入有很多种,有scanf,cin,cin.getline……

但本题我推荐用getline(cin , 数组名) 输入,因为输入包括空格,这种是最方便的。

下面献上输入代码:

C++
string s1 , s2; //string可以无限大
getline(cin , s1);
getline(cin , s2);

2. 转 大/小 写

接下来就是统一大小写,本人建议所有都统一小写

先来认识一下两个函数

toltwer() 大写转小写 如 AA —> aa。

toupper() 小写转大写 如 aa —> AA。

下面献上转小写代码:

C++
for(int i = 0;i < s1.length();i++)
	s1[i] = tolower(s1[i]);
for(int i = 0;i < s2.length();i++)
	s2[i] = tolower(s2[i]);
// 全部转小写

转大写代码:

C++
for(int i = 0;i < s1.length();i++)
	s1[i] = toupper(s1[i]);
for(int i = 0;i < s2.length();i++)
	s2[i] = toupper(s2[i]);
// 全部转大写

3. 加空格

这就不用多说了吧?只要两头加空格就行了:

C++
s1 = ' ' + s1 + ' ';
s2 = ' ' + s2 + ' ';

4. 开始寻找

4.1使用 find()find() 函数查特例

先介绍一下 findfind 函数

findfind 查找的意思,主要用法为:

单词序列.find(查找内容) != string::npos (说明找到了)

单词序列.find(查找内容) == string::npos (说明没找到)

那么判特例就是没找到,所以应该用第 2 行代码

C++
if(s2.find(s1) == string::npos){ // npos == >endposition
// 找不到输出 -1 , 结束程序
   cout << "-1" << endl;
   return 0;
}

4.2使用 find()find() 计数

这里要声明一下, findfind 函数十分奇特,找到了他就不找了,所以我们要用 while() 将他一直重复:

C++
int pos = 0 , ans = 0 , cnt = 0; // 全部清零
pos = s2.find(s1); // 找第一个索引
ans = pos;
while(pos != string::npos){
   cnt++; // 如果找到了,那就计数 +1
   pos = s2.find(s1 , pos+1); // 从 pos+1 处开始找
}

5. 完美输出

C++
cout << cnt << " " << ans;

好了,这就是步骤,下面献上完整code:

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
    string s1 , s2;
    getline(cin , s1);
    getline(cin , s2);
    //用 getline 读入

    for(int i = 0;i < s1.length();i++)
        s1[i] = tolower(s1[i]);
    for(int i = 0;i < s2.length();i++)
        s2[i] = tolower(s2[i]);
    // 全部转小写

    s1 = ' ' + s1 + ' ';
    s2 = ' ' + s2 + ' ';
    // 加空格 , 以便搜索
    // 注:像样例一 防止像 tomato 这样的单词

    // 使用 find 函数 , 更便捷
    if(s2.find(s1) == string::npos){ // npos == endposition
        // 找不到输出 -1 , 结束程序
        cout << "-1" << endl;
        return 0;
    }
    int pos = 0 , ans = 0 , cnt = 0; // 全部清零
    pos = s2.find(s1); // 找第一个索引
    ans = pos;
    while(pos != string::npos){
        cnt++; // 如果找到了,那就计数 +1
        pos = s2.find(s1 , pos+1); // 从 pos+1 处开始找
    }
    cout << cnt << " " << ans;
    return 0;
}
原文