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;
}

运行结果


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM