用string的find()快速找到子字串的開頭位置,如果沒有則回傳string::npos。
不過這樣找也有可能會找到錯誤的,像是找單字:to
如果有一個單字叫otto或tto之類有包含to兩字母的話,也會誤以為找到。
因此則改成找單字且前後都有空格的話才算是找到,也因此句子裡每一個單字前後也都要有空白,所以才有那兩行奇怪的操作。
程式碼:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int count=0;
string s,word,tmp;
getline(cin,word);
getline(cin,s);
for(int i=0;i<word.size();i++)
word[i]=tolower(word[i]);
for(int i=0;i<s.size();i++){
s[i]=tolower(s[i]);
}
stringstream ss(s);
while(ss>>tmp)
{
if(tmp==word)
count++;
}
word=' '+word+' ';
s=' '+s+' ';
if(s.find(word)!=string::npos) cout<<count<<" "<<s.find(word)<<endl;
else cout<<-1<<endl;
return 0;
}
沒有留言:
張貼留言