如果s是a std::string,那么是否有如下函数?
s.replace("text to replace", "new text");
Run Code Online (Sandbox Code Playgroud)
Mat*_*haq 80
尝试结合使用std::string::find和std::string::replace.
这得到了这个位置:
std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);
Run Code Online (Sandbox Code Playgroud)
这取代了第一次出现:
s.replace(pos, toReplace.length(), "new text");
Run Code Online (Sandbox Code Playgroud)
现在您可以简单地创建一个功能,以方便您:
std::string replaceFirstOccurrence(
std::string& s,
const std::string& toReplace,
const std::string& replaceWith)
{
std::size_t pos = s.find(toReplace);
if (pos == std::string::npos) return s;
return s.replace(pos, toReplace.length(), replaceWith);
}
Run Code Online (Sandbox Code Playgroud)
Cza*_*zak 27
我们真的需要一个看似如此简单的任务的Boost库吗?
要替换子串的所有出现,请使用以下函数:
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
Run Code Online (Sandbox Code Playgroud)
如果您需要性能,这里是一个修改输入字符串的优化函数,它不会创建字符串的副本:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Run Code Online (Sandbox Code Playgroud)
测试:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
Run Code Online (Sandbox Code Playgroud)
pho*_*oji 23
是:replace_all是增强字符串算法之一:
虽然它不是标准库,但它在标准库上有一些东西:
replace_all嵌套在a中trim).这对于标准库函数来说更复杂一些.Mar*_*nen 10
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str("one three two four");
string str2("three");
str.replace(str.find(str2),str2.length(),"five");
cout << str << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
one five two four
Run Code Online (Sandbox Code Playgroud)
小智 7
像有人说boost :: replace_all
这是一个虚拟的例子:
#include <boost/algorithm/string/replace.hpp>
std::string path("file.gz");
boost::replace_all(path, ".gz", ".zip");
Run Code Online (Sandbox Code Playgroud)