数据结构-find()-判断字符串s1中是否包含字符串s2
find()库函数
#include <iostream>
using namespace std;bool check(string s1,string s2){int n = s1.size();int m = s2.size();if(n==0||m==0 || n<m){return false;}if(s1.find(s2) != string::npos){return true;}else{return false;}
}int main ()
{string a = "Hello, world!";string b = "worlds";if(check(a,b)){cout<<"yes"<<endl;}else{cout<<"no"<<endl;}return 0;
}
不使用库函数
#include <iostream>
using namespace std;bool check(string s1,string s2){int n = s1.size();int m = s2.size();int j = 0;if(n<m){return false;}if(m == 0){return true;}for(int i = 0;i<n;i++){if(s1[i] == s2[0]){//第一个字符匹配 j=0; }while(s1[i] == s2[j]){ //匹配后面的字符 i++;j++;}if(j == m){ //如果j与s2的长度相同,说明匹配成功 return true;break;}}return false;
} int main() {string s1 = "hello word!";string s2 = "llo";cout<<check(s1,s2)<<endl;return 0;
}