对于 std::string
s,如何用另一个字符串替换所有出现的子字符串?
std::string s ("One hello, two hellos.");
s = s.replace("hello", "world"); // something like this
原文由 Adam Tegen 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于 std::string
s,如何用另一个字符串替换所有出现的子字符串?
std::string s ("One hello, two hellos.");
s = s.replace("hello", "world"); // something like this
原文由 Adam Tegen 发布,翻译遵循 CC BY-SA 4.0 许可协议
许多其他答案重复调用 std::string::replace
,这需要重复覆盖字符串,导致性能不佳。相比之下,这使用 std::string
缓冲区,以便字符串的每个字符只遍历一次:
void replace_all(
std::string& s,
std::string const& toReplace,
std::string const& replaceWith
) {
std::string buf;
std::size_t pos = 0;
std::size_t prevPos;
// Reserves rough estimate of final size of string.
buf.reserve(s.size());
while (true) {
prevPos = pos;
pos = s.find(toReplace, pos);
if (pos == std::string::npos)
break;
buf.append(s, prevPos, pos - prevPos);
buf += replaceWith;
pos += toReplace.size();
}
buf.append(s, prevPos, s.size() - prevPos);
s.swap(buf);
}
用法:
replace_all(s, "text to replace", "new text");
#include <iostream>
#include <sstream>
void replace_all(
std::string& s,
std::string const& toReplace,
std::string const& replaceWith
) {
std::string buf;
std::size_t pos = 0;
std::size_t prevPos;
// Reserves rough estimate of final size of string.
buf.reserve(s.size());
while (true) {
prevPos = pos;
pos = s.find(toReplace, pos);
if (pos == std::string::npos)
break;
buf.append(s, prevPos, pos - prevPos);
buf += replaceWith;
pos += toReplace.size();
}
buf.append(s, prevPos, s.size() - prevPos);
s.swap(buf);
}
int main() {
std::string s("hello hello, mademoiselle!");
replace_all(s, "hello", "bye");
std::cout << s << std::endl;
}
输出:
bye bye, mademoiselle!
注意: 此答案的先前版本使用 std::ostringstream
,这有一些开销。根据@LouisGo 的建议,最新版本使用 std::string::append
代替。
原文由 Mateen Ulhaq 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
为什么不实施自己的替换?