如果s
是std::string
,那么有没有类似下面的函数?
s.replace("text to replace", "new text");
最佳答案
替换第一个匹配项
使用 std::string::find
的组合和 std::string::replace
.
找到第一个匹配项:
std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);
替换第一个匹配项:
s.replace(pos, toReplace.length(), "new text");
为您提供方便的简单功能:
void replace_first(
std::string& s,
std::string const& toReplace,
std::string const& replaceWith
) {
std::size_t pos = s.find(toReplace);
if (pos == std::string::npos) return;
s.replace(pos, toReplace.length(), replaceWith);
}
用法:
replace_first(s, "text to replace", "new text");
替换所有匹配项
使用 std::string
定义此 O(n) 方法作为缓冲区:
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");
提升
或者,使用 boost::algorithm::replace_all
:
#include <boost/algorithm/string.hpp>
using boost::replace_all;
用法:
replace_all(s, "text to replace", "new text");
关于c++ - 如何查找和替换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5878775/