用另一个子字符串 C++ 替换子字符串

2021-12-25 00:00:00 string replace substring c++ c++11

如何用 C++ 中的另一个子字符串替换字符串中的一个子字符串,我可以使用哪些函数?

How could I replace a substring in a string with another substring in C++, what functions could I use?

eg: string test = "abc def abc def";
test.replace("abc", "hij").replace("def", "klm"); //replace occurrence of abc and def with other substring

推荐答案

在 c++11,你可以使用 std::regex_replace:

In c++11, you can use std::regex_replace:

#include <string>
#include <regex>

std::string test = "abc def abc def";
test = std::regex_replace(test, std::regex("def"), "klm"); // replace 'def' -> 'klm'
// test = "abc klm abc klm"

相关文章