求助,悬关~

P1308 [NOIP2011 普及组] 统计单词数

@[lucy2012](/user/1252442) `str.find()` 可以带第二个参数,即查找 str 串的开始下标。参数值默认为 $0$。
by Carroty_cat @ 2024-02-22 12:31:28


@[Carroty_cat](/user/912750) 可以怎么改呢?
by lucy2012 @ 2024-02-22 12:35:08


@[lucy2012](/user/1252442) 我觉得应该是因为你没有判断单词左右两边是否为空格
by Into_the_Abyss @ 2024-02-22 12:53:22


@[lucy2012](/user/1252442) 我给你改下康康
by Into_the_Abyss @ 2024-02-22 12:53:48


@[lucy2012](/user/1252442) ```cpp #include<bits/stdc++.h> using namespace std; int main(){ string s,a; int sum=0,w; getline(cin,a); getline(cin,s); for(int i=0;i<a.length();i++) a[i]=tolower(a[i]); for(int i=0;i<s.length();i++) s[i]=tolower(s[i]); s=' '+s+' '; a=' '+a+' '; if (s.find(a)==string::npos){ cout<<-1<<"\n"; return 0; } int firstpos=s.find(a,0),pos=s.find(a,0); while(pos!=string::npos){ pos=s.find(a,pos+1); sum++; } cout<<sum<<' '<<firstpos<<"\n"; return 0; } ```
by Into_the_Abyss @ 2024-02-22 13:21:39


@[YJHtbyz](/user/1223722) @[lucy2012](/user/1252442) ```cpp #include<bits/stdc++.h> using namespace std; int main(){ string s,a; int sum=0; getline(cin,a); getline(cin,s); for(int i=0;i<a.length();i++) a[i]=tolower(a[i]); for(int i=0;i<s.length();i++) s[i]=tolower(s[i]); s=' '+s+' ';//在文章前后加上空格方便判断 a=' '+a+' ';//在单词前后加上空格方便判断 if (s.find(a)==string::npos){ cout<<-1<<"\n"; return 0; }//如果未找到,直接打印-1退出程序 int firstpos=s.find(a,0),pos=s.find(a,0);//定义firstpos记录初始位置,pos从第一次出现的位置开始 while(pos!=string::npos){ pos=s.find(a,pos+1);//pos找到后向后移动一位,否则会一直返回第一次找到的地址 sum++;//找到一个计数器++ } cout<<sum<<' '<<firstpos<<"\n";//最后打印 return 0; } ```
by Into_the_Abyss @ 2024-02-22 13:27:33


@[YJHtbyz](/user/1223722) 谢啦
by lucy2012 @ 2024-02-22 13:33:48


|