问题
现有两个字符串a和b, 想判断a字符串是否包含b字符串,该如何设计程序?LeetCode上有道题会用到。
思路
此处就需要用到string库中的find函数与npos参数。
先说说string::npos参数:
npos 是一个常数,用来表示不存在的位置,类型一般是std::container_type::size_type 许多容器都提供这个东西;取值由实现决定,一般是-1,这样做,就不会存在移植的问题。
再来说说find函数:
find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系;那么返回值就一定是npos,所以很容易想到用if判断语句来实现。
简单而言:如果存在包含关系find函数返回的就是主串与子串相匹配的下标,如果不存在包含关系就返回。
npos(一个常数,表示不存在)(s.find(“abcdefg”)==string::npos)
if (a.find(b) != string::npos)
{
cout << "a contains b" << endl;
}
else
{
cout << "a does not contain b" << endl;
}
# include <iostream>
# include <string>
using namespace std;
int main()
{
int number;
cin >> number;
while (number--)
{
string a, b;
cin >> a >> b;
int pos = a.find(b);
if (pos == string::npos)
{
cout << "no" << endl;
}
else
{
cout << "yes" << endl;
}
}
}