C++ string determines whether it contains a substring

string class function find

The string class of C++ provides the function find to find another string in a string.

Its overloaded form is:

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

The function is to find whether the string of the parameter string type exists in the string object, and return the starting position if it exists. Returns if not present string::npos.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
    string a="abcdefghigklmn";
    string b="def";
    string c="123";
    string::size_type idx;
     
    idx=a.find(b);//在a中查找b.


    if(idx == string::npos )//不存在。
        cout << "not found\n";
    else//存在。
        cout <<"found\n"; 

    idx=a.find(c);//在a中查找c。
    if(idx == string::npos )//不存在。
        cout << "not found\n";
    else//存在。
        cout <<"found\n"; 
    return 0;
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_64632836/article/details/130473965