如何在 C++ 中替换字符串的一部分

本文演示了多种关于在 C++ 中如何替换字符串的一部分的方法。

在 C++ 中使用 replace() 方法替换字符串的一部分

replacestd::string 类的内置方法,它提供了替换字符串对象中给定部分的确切功能。该函数的第一个参数表示插入给定字符串的起始字符。下一个参数指定应该被新字符串替换的子字符串的长度。最后,新字符串作为第三个参数传递。注意,replace() 方法会修改被调用的字符串对象。

#include <iostream>#include <string>using std::cout; using std::cin;
using std::endl; using std::string;
int main(){
    string input = "Order $_";
    string order = "#1190921";
    cout << input << endl;
    input.replace(input.find("$_"), 2, order);
    cout << input << endl;
    return EXIT_SUCCESS;
}

输出:

Order $_
Order #1190921

使用自定义函数替换 C++ 中的部分字符串

或者,你可以构建一个自定义函数,返回一个单独的修改后的字符串对象,而不是在原地进行替换。该函数接收 3 个对字符串变量的引用:第一个字符串用于修改,第二个子字符串用于替换,第三个字符串用于插入。在这里,你可以注意到,由于函数具有移动语义,所以它通过值返回构造的字符串。

#include <iostream>#include <string>using std::cout; using std::cin;
using std::endl; using std::string;
string Replace(string& str, const string& sub, const string& mod) {
    string tmp(str);
    tmp.replace(tmp.find(sub), mod.length(), mod);
    return tmp;
}
int main(){
    string input = "Order $_";
    string order = "#1190921";
    cout << input << endl;
    string output = Replace(input, "$_", order);
    cout << output << endl;
    return EXIT_SUCCESS;
}

输出:

Order $_
Order #1190921

使用 regex_replace() 方法替换 C++ 中的部分字符串

另一个可以用来解决这个问题的有用方法是利用 regex_replace;它是 STL 正则表达式库的一部分,定义在 <regex> 头文件。该方法使用 regex 来匹配给定字符串中的字符,并将序列替换为一个传递的字符串。在下面的例子中,regex_replace 构建了一个新的字符串对象。

#include <iostream>#include <string>#include <regex>using std::cout; using std::cin;
using std::endl; using std::string;
using std::regex_replace; using std::regex;
int main(){
    string input = "Order $_";
    string order = "#1190921";
    cout << input << endl;
    string output = regex_replace(input, regex("\\$_"), order);
    cout << output << endl;
    return EXIT_SUCCESS;
}

输出:

Order $_
Order #1190921