刷到最后一道字符串相關的題目,搜索題解發現神奇算法 strstr,為了防止自己以后遺忘,所以特意開篇文章,來說明用法以及注意事項;
頭文件:
#include<cstring>
函數原型:
char *strstr(const char *str1, const char *str2);
函數用法:
此函數的功能為查詢字符串 str2 是否是 str1 的子串,如果是,返回字符串str2在str1中出現的頭一個位置的指針*char。如果不是,則返回null;
根據以上,此函數可以有兩個用法:
① 判斷一字符串是否為另一字符串的子串:
#include<iostream> #include<cstring> using namespace std; char a[100010],b[100010]; int main() { cin>>a; cin>>b; if(!strstr(a,b)) { cout<<"no"<<endl; }else{ cout<<"yes"<<endl; } }
輸入輸出:
②用來尋找子串出現的位置的下標:
#include<iostream> #include<cstring> using namespace std; char a[100010],b[100010]; int main() { cin>>a; cin>>b; if(!strstr(a,b)) { cout<<"no"<<endl; }else{ cout<<strstr(a,b) - a<<endl; } }
③如果是子串,還可以用來輸出子串以及以后的字符:
#include<iostream> #include<cstring> using namespace std; char a[100010],b[100010]; int main() { cin>>a; cin>>b; if(!strstr(a,b)) { cout<<"no"<<endl; }else{ cout<<strstr(a,b)<<endl; } }