如何判断一个字符串是否包含在另一个字符串中

how to tell if a string is contained in another string

本文关键字:字符串 包含 是否 另一个 何判断 判断 一个      更新时间:2023-10-16

C++代码。示例:x: "这是#我的第一个程序";y: "#my";

bool function(string x, string y)
{
//Return true if y is contained in x
return ???; 
}

您可以使用std::string::find()

bool function(string x, string y)
{
    return (x.find(y) != std::string::npos);
}

您可以使用string:find

如何编写函数取决于搜索空字符串是否成功。如果考虑在任何字符串中都存在空字符串,则函数将看起来像

bool function( const std::string &x, const std::string string &y )
{
    return ( x.find( y ) != std::string::npos );
}

如果考虑对空字符串的搜索将返回false,则函数将看起来像

bool function( const std::string &x, const std::string string &y )
{
    return ( !y.empty() && x.find( y ) != std::string::npos );
}

对于空字符串,我更希望函数返回false。