C++|string字符串操作(切割,是否包含某个子串)

C++字符串切割主要用到string的两个函数 find()和substr(),先用find函数找到需要切割的位置,再用substr进行切割,示例程序如下:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "Hello World!";
    cout << str << endl;
    string::size_type comper = str.find(" ");
    string a = str.substr(0, comper);
    cout << a << endl;
    string b = str.substr(comper+1, str.size());
    cout << b << endl;
}

判断字符串中是否包含某个子串:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "Hello World!";
    cout << str << endl;
    string::size_type comper = str.find("Hello");
    if (comper != string::npos) {
        cout << "str中包含Hello";
    }
    else {
        cout << "str中不包含Hello";
    }
}

版权声明:本文为weixin_42964413原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。