C/C++:子串判断

一、子串判断

题目描述

我们定义字符串包含关系:字符串A=abc,字符串B=ab,字符串C=ac,则说A包含B,A和C没有包含关系。

输入描述:

两个字符串,判断这个两个字符串是否具有包含关系,测试数据有多组,请用循环读入。

输出描述:

如果包含输出1,否则输出0.

输入

abc ab

输出

1

1、C风格,strstr()

char *strstr(const char *str1, const char *str2);

如果str2是str1的子串,返回指针位置;否则,返回空指针。

#include <iostream> #include <string> #include <cstring> using namespace std; int main() { string s1, s2; while(cin >> s1 >> s2) { if(s1.size() >= s2.size()) cout << (strstr(s1.c_str(), s2.c_str()) != nullptr) << endl; //换行有坑!!! else cout << (strstr(s2.c_str(), s1.c_str()) != nullptr) << endl; } return 0; }

2、C++风格,find()

string::size_type string::find(string &);

在string对象中,查找参数string类型的字符串是否存在。如果存在,返回起始位置(string::size_type类型);不存在则返回 string::npos。

#include <iostream> #include <string> #include <cstring> using namespace std; int main() { string s1, s2; while(cin >> s1 >> s2) { if(s1.size() >= s2.size()) cout << (s1.find(s2) != string::npos) << endl; else cout << (s2.find(s1) != string::npos) << endl; } return 0; }