通常的文本編輯器都有查找單詞的功能,該功能能夠快速定位特定單詞在文章中的位置,有的還能統計出特定單詞在文章中出現的次數。php
如今,請你編程實現這一功能,具體要求是:給定一個單詞,請你輸出它在給定的文章中出現的次數和第一次出現的位置。注意:匹配單詞時,不區分大小寫,但要求徹底匹配,即給定單詞必須與文章中的某一獨立單詞在不區分大小寫的狀況下徹底相同(參見樣例1),若是給定單詞僅是文章中某一單詞的一部分則不算匹配(參見樣例2)。ios
第 1 行爲一個字符串,其中只含字母,表示給定單詞;編程
第 2 行爲一個字符串,其中只可能包含字母和空格,表示給定的文章。編輯器
只有一行,若是在文章中找到給定單詞則輸出兩個整數,兩個整數之間用一個空格隔開,分別是單詞在文章中出現的次數和第一次出現的位置(即在文章中第一次出現時,單詞首字母在文章中的位置,位置從0開始);若是單詞在文章中沒有出現,則直接輸出一個整數-1。spa
To to be or not to be is a question
2 0
樣例輸入:code
樣例 #2:blog
toci
Did the Ottoman Empire lose its power at that time字符串
樣例輸出:get
樣例 #2:
-1
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; int ans=0,pos=-1; char s1[15],s2[1000005],s3[1000005]; int main() { gets(s1); gets(s2); int len1=strlen(s1),len2=strlen(s2); s3[0]=' ';s3[1]='\0'; strcat(s3,s2); s2[0]=' ';s2[1]='\0'; strcat(s3,s2); for (int i=len2-len1+1;i>=1;i--)//從後往前遍歷 { strncpy(s2,s3+i,len1);s2[len1]='\0'; if (s3[i-1]==' '&&s3[i+len1]==' '&&strcmp(strlwr(s1),strlwr(s2))==0) {ans++;pos=i-1;} } if (pos!=-1) printf("%d ",ans); printf("%d\n",pos); printf("\n"); return 0; }
#include<iostream> #include<string> using namespace std; string s1,s2; int ans=0,pos=-1; int main() { getline(cin,s1); getline(cin,s2); s1.insert(0," "); s1.insert(s1.size()," "); s2.insert(0," "); s2.insert(s2.size()," "); for (int i=0;i<s1.size();i++) if (s1[i]>='A'&&s1[i]<='Z') s1[i]+=32; for (int i=0;i<s2.size();i++) if (s2[i]>='A'&&s2[i]<='Z') s2[i]+=32; while ((pos=s2.find(s1,pos+1))!=string::npos)//查找有匹配 ans++; if (ans) cout<<ans<<" "<<s2.find(s1,0)<<endl; else cout<<-1<<endl; return 0; }