题目类型:字符串
题目来源:https://www.luogu.org/problemnew/solution/P1308
思路:
【1】查找单词出现的第一次位置可以使用string::find()函数,主要要在目标单词旁边各加一个空格
【2】统计单词个数,可以使用记录状态来,看代码
代码
#include <iostream>
#include <string>
#include <string.h>
#include <vector>
#include <stdio.h>
#include <algorithm>
using namespace std;
int total;
char word[15];
char artice[1000005];
void tolow();
void coun();
int main(){
gets(word);
gets(artice);
tolow();
coun();
string str(artice);
string str2(word);
str = ' '+str;
size_t startIndex = str.find(' '+str2+' ');
if(startIndex == string::npos)
cout<<"-1";
else
cout<<total<<" "<< startIndex;
return 0;
}
void tolow(){ //将所有的大写字母改成小写
for(int i = 0;artice[i]!='\0';i++){
artice[i] = (char)tolower(artice[i]);
}
for(int i = 0;word[i]!='\0';i++){
word[i] = (char)tolower(word[i]);
}
}
void coun(){//统计目标单词个数
bool sign = false;//false--不能开始匹配 true---可以开始匹配
for(int i = 0;artice[i]!='\0';){
if(sign){//开始匹配
int j;
for(j = 0;word[j]!='\0'&&artice[i]!='\0'&&artice[i]!=' ';j++,i++){ //一一匹配
if(word[j]!=artice[i]){
break;
}
}
if(word[j] == '\0' && (artice[i] == ' '||artice[i]=='\0')){
total++;//单词数+1
}
for(;artice[i]!=' '&&artice[i]!='\0';i++){//匹配失败后,跳过无效的字母
;
}
sign = false;
}else{//跳过空格
for(;artice[i]==' ';i++){
;
}
sign = true;
}
}
}