一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。 现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。
注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同(参见样例1),如果给定单词仅是文章中某一单词的一部分则不算匹配(参见样例2)。
【输入】 第 1 行为一个字符串,其中只含字母,表示给定单词; 第 2 行为一个字符串,其中只可能包含字母和空格,表示给定的文章。
【输出】只有一行,如果在文章中找到给定单词则输出两个整数,两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从0开始);如果单词在文章中没有出现,则直接输出一个整数-1。
【输入样例】 To to be or not to be is a question
【输出样例】 2 0
样例输入:样例 #2: to Did the Ottoman Empire lose its power at that time 样例输出: 样例 #2: -1
请问用c++函数怎么写。麻烦注释一下。最好不要用到函数以后的知识。
谢谢!!
#include
#include
#include
#include
using namespace std;
int main()
{
string word,sentence;
int i,j;
int lena,lenb;
int ans = 0,dir;
getline(cin,word);//输入单词
getline(cin,sentence);//输入句子
lena = word.size();//记录单词的长度
lenb = sentence.size();//记录句子的长度
for(i = 0; i < lenb; i++)
{
for(j = 0; j < lena; j++)
{
if(toupper(sentence[i+j]) != toupper(word[j]))
break;//若字符不匹配退出循环,再从第i+1个开始判定
if(i > 0 && sentence[i-1] != ' ')
break;//若第i个字符不是文章首且前一个字符不是空格,则不是独立单词,退出
}
if(j == lena && (sentence[i+j] == ' ' || j + i == lenb))//若循环判定通过,且该单词词尾为文章尾或后有空格
{
ans++;//累加满足条件单词数
if(ans == 1)//若第一次出现
dir = i;//记录位置
}
}
if(ans)
cout << ans <<" "<< dir << endl;
else
cout << "-1" << endl;
return 0;
}
#include
#include
#include
#include
using namespace std;
int main()
{
string word,sentence;
int i,j;
int lena,lenb;
int ans = 0,dir;
getline(cin,word);//输入单词
getline(cin,sentence);//输入句子
lena = word.size();//记录单词的长度
lenb = sentence.size();//记录句子的长度
for(i = 0; i < lenb; i++)
{
for(j = 0; j < lena; j++)
{
if(toupper(sentence[i+j]) != toupper(word[j]))
break;//若字符不匹配退出循环,再从第i+1个开始判定
if(i > 0 && sentence[i-1] != ' ')
break;//若第i个字符不是文章首且前一个字符不是空格,则不是独立单词,退出
}
if(j == lena && (sentence[i+j] == ' ' || j + i == lenb))//若循环判定通过,且该单词词尾为文章尾或后有空格
{
ans++;//累加满足条件单词数
if(ans == 1)//若第一次出现
dir = i;//记录位置
}
}
if(ans)
cout << ans <<" "<< dir << endl;
else
cout << "-1" << endl;
return 0;
}
if(s[i] >= 'A' && s[i] <= 'Z')
s[i] = s[i] - 'A' + 'a';
} if(s[i] == ' ' || s[i] == '\0')//如果完成读取一个单词
{
if(k == lenw)//如果在s中遍历的长度与单词word的长度相同,即找到一个和word相同的单词
{
ct++;//技术
if(firstPos == -1)//记录第一次出现的位置
firstPos = i - lenw;//当前位置i是单词后的空格的位置,减去lenw后即为单词第一个字符的位置
}
k = 0;//k还原为0,准备看下一个单词是否与word相同
}
else
{
if(k >= 0)//如果k>=0,说明s中有部分与word相同。如果k为-1,说明这个单词与word不同。
{
if(word[k] == s[i])
k++;
else
k = -1;
}
}
} cout << -1;
else//如果存在 cout << ct << ' ' << firstPos;
return 0;#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
string s,sf;
int t;
int main(){
getline(cin,sf);
getline(cin,s);
int j;
for(j=0;j<=sf.size();j++)
sf[j]=tolower(sf[j]);
for(j=0;j<=s.size();j++)
s[j]=tolower(s[j]);
sf=' '+sf+' ';
s=' '+s+' ';
int posi=-1;
int fpos=0;
if(s.find(sf)==string::npos){
cout<<"-1";
return 0;
}
fpos=s.find(sf);
while(s.find(sf,posi+1)!=string::npos){
posi=s.find(sf,posi+1);
t++;
}
cout<<t<<" "<<fpos;
return 0;
}
https://blog.csdn.net/wzw1376124061/article/details/51887603