【题目描述】
一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。
现在,请你编程实现这一功能。
具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。
注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同(参见样例1),如果给定单词仅是文章中某一单词的一部分则不算匹配(参见样例2)。
【输入格式】
第1行为一个字符串,其中只含字母,表示给定单词;
第2行为一个字符串,其中只可能包含字母和空格,表示给定的文章。
【输出格式】
只有一行,如果在文章中找到给定单词则输出两个整数,两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从 0 开始);如果单词在文章中没有出现,则直接输出一个整数-1。
【测试样例】
输入样例1:
To
to be or not to be is a question
输出样例1:
2 0
输入样例2:
to
Did the Ottoman Empire lose its power at that time
输出样例2:
-1
【数据范围】
1≤ 单词长度≤10
1≤ 文章长度≤1,000,000
【算法代码】
#include <bits/stdc++.h>
using namespace std;
int main() {
string a,b;
getline(cin,a); //word
getline(cin,b); //article
for(int i=0; i<a.size()-1; i++) a[i]=tolower(a[i]);
for(int i=0; i<b.size()-1; i++) b[i]=tolower(b[i]);
a=" "+a+" "; //防止识别仅是某一单词一部分的情况
b=" "+b+" "; //防止识别仅是某一单词一部分的情况
if(b.find(a)==-1)
cout<<"-1"<<endl;
else {
int idx=b.find(a); //返回a在b中的下标
int t=idx;
int ans=0;
while(t!=-1) {
ans++;
t=b.find(a,t+1); //从字符串b的下标t+1开始查找字符串a,返回a在b中的下标
}
cout<<ans<<" "<<idx;
}
return 0;
}
/*
in1:
To
to be or not to be is a question
out1:
2 0
-------------------
in2:
to
Did the Ottoman Empire lose its power at that time
out2:
-1
*/
【参考文献】
https://blog.csdn.net/xingzhe_666/article/details/102498998
https://www.cnblogs.com/cangT-Tlan/p/7896641.html
https://blog.csdn.net/qq_45710757/article/details/104128602