問題描述
c++ 查找和替換整個單詞 (c++ Find and replace whole word)
我如何查找和替換(匹配整個單詞)。我有這個。
void 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();
}
}
但它不會搜索整個單詞。例如,如果我嘗試
string test = "i like cake";
ReplaceString(test, "cak", "notcake");
它仍然會替換,但我希望它匹配整個單詞。
參考解法
方法 1:
You're just blindly replacing any instances of search
with replace
without checking if they're full words prior to performing the replacement.
Here are just a couple of things you can try to work around that:
- Split the string into individual words, then check each word against
search
, and replace if necessary. Then rebuild the string. - Replace only if
pos‑1
andpos + search.length() + 1
are both spaces.
(by Real Zibux、lcs)