如何在c ++中搜索另一个字符串中的字符串?

-2 c++ string search char

int main(){
string s1="gandalf";
string s2="dal";
function(s1,s2);
return 0;

}
Run Code Online (Sandbox Code Playgroud)

在函数中,如果字符串s1中有"dal",则返回1. else返回0

Vla*_*cow 6

请尝试以下方法

bool function( const std::string &s1, const std::string &s2 )
{
    return s1.find( s2 ) != std::string::npos;
}
Run Code Online (Sandbox Code Playgroud)

如果你想使用循环自己编写函数,那么它可以采用以下方式

#include <iostream>
#include <iomanip>
#include <string>

bool function( const std::string &s1, const std::string &s2 )
{
    bool found = false;

    if ( !( s1.size() < s2.size() ) && !s2.empty() )
    {
        for ( size_t i = 0; !found && i < s1.size() - s2.size() + 1; i++ )
        {
            size_t j = 0;
            while ( j < s2.size() && s1[i+j] == s2[j] ) ++j;
            found = j == s2.size();
        }
    }

    return found;
}

int main() 
{
    std::string s1 = "gandalf";
    std::string s2 = "dal";

    std::cout << std::boolalpha << function( s1, s2 ) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

程序输出是

true
Run Code Online (Sandbox Code Playgroud)