公告
财富商城
积分规则
提问
发文
2020-01-25 05:45发布
乱世女痞
If s is a std::string, then is there a function like the following?
s
std::string
s.replace("text to replace", "new text");
Try a combination of std::string::find and std::string::replace.
std::string::find
std::string::replace
This gets the position:
std::string s; std::string toReplace("text to replace"); size_t pos = s.find(toReplace);
And this replaces the first occurrence:
s.replace(pos, toReplace.length(), "new text");
Now you can simply create a function for your convenience:
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); }
Here's the version I ended up writing that replaces all instances of the target string in a given string. Works on any string type.
template <typename T, typename U> T &replace ( T &str, const U &from, const U &to) { size_t pos; size_t offset = 0; const size_t increment = to.size(); while ((pos = str.find(from, offset)) != T::npos) { str.replace(pos, from.size(), to); offset = pos + increment; } return str; }
Example:
auto foo = "this is a test"s; replace(foo, "is"s, "wis"s); cout << foo;
Output:
thwis wis a test
Note that even if the search string appears in the replacement string, this works correctly.
#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; }
one five two four
最多设置5个标签!
Try a combination of
std::string::find
andstd::string::replace
.This gets the position:
And this replaces the first occurrence:
Now you can simply create a function for your convenience:
Here's the version I ended up writing that replaces all instances of the target string in a given string. Works on any string type.
Example:
Output:
Note that even if the search string appears in the replacement string, this works correctly.
Output