C++string字符串截取其中元素 截取定位字符串

#include <iostream>
#include <string>

using namespace std;

/**
 * 截取str后的元素
 * @param stream 待截取字符串
 * @param str 截取定位字符串
 * @return
 */
static auto cutNext(string stream, const string &str) {
    int nPos = stream.find(str);

    if (nPos != -1) {
        stream = stream.substr(nPos + str.size(), stream.size());
    }
    return stream;
}

/**
 * 截取str前的元素
 * @param stream 待截取字符串
 * @param str 截取定位字符串
 * @return
 */
static auto cutPre(string stream, const string &str) {
    int nPos = stream.find(str);
    if (nPos != -1) {
        stream = stream.substr(0, nPos);
    }
    return stream;
}

int main() {
    string str = "helloworld";
    string str_pre = cutPre(str, "world");
    string str_next = cutNext(str, "hello");
    cout << "str=" << str << endl;
    cout << "str_next=" << str_next << endl;
    cout << "str_pre=" << str_pre << endl;
}

运行结果

posted @ 2020-09-26 11:51  Xu_Lin  阅读(7133)  评论(0编辑  收藏  举报