【问题标题】:how to tell if a string is contained in another string [duplicate]如何判断一个字符串是否包含在另一个字符串中[重复]
【发布时间】:2014-06-10 03:55:59
【问题描述】:

C++ 代码。 例子: x: "这是#我的第一个节目"; y:“#我的”;

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

return ???; 
}

【问题讨论】:

  • Stack Overflow 并不是一个神奇的代码生成器。

标签: c++ string


【解决方案1】:

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

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

【讨论】:

  • std::search,适用于任何序列。
【解决方案2】:

您可以使用 string::find

做到这一点

【讨论】:

    【解决方案3】:

    函数的编写方式取决于对空字符串的搜索是否会被视为成功。 如果考虑到任何字符串中都存在空字符串,则该函数将如下所示

    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。

    【讨论】:

      猜你喜欢
      • 2011-02-05
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      相关资源
      最近更新 更多