c++ 查找和替換整個單詞 (c++ Find and replace whole word)


問題描述

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 and pos + search.length() + 1 are both spaces.

(by Real Zibuxlcs)

參考文件

  1. c++ Find and replace whole word (CC BY‑SA 2.5/3.0/4.0)

#find #replace #C++






相關問題

禁止查找和 grep“無法打開”輸出 (Suppress find & grep "cannot open" output)

Cakephp 複雜查詢 (Cakephp complex query)

如何在 hasMany 關聯中使用 CakePHP 2 查找? (How to use CakePHP 2 find in a hasMany association?)

Jquery 響應 find() 失敗? (Jquery respond to find() fail?)

正則表達式記事本++ (RegEx Notepad++)

使用 VBA 在 MS Word 表格中查找和替換可變長度文本 (Find & replace variable length text in MS Word tables using VBA)

獲取子字符串周圍的字符數半徑 (Get set number radius of characters around substring)

僅在不到一天的文件中搜索字符串 (Search for a string only in files less than a day old)

c++ 查找和替換整個單詞 (c++ Find and replace whole word)

使用 grep 過濾後如何忽略行首和行的一部分 (How to ignore beginning of line and parts of a line after filtering with grep)

查找函數加上循環給出 1004 錯誤 (Find function couple with loop gives 1004 error)

VS Code 查找和替換:當我輸入 ctrl+h 時,有沒有辦法保留我以前的查找項? (VS Code find-and-replace: is there a way to keep my previous find term when I type ctrl+h?)







留言討論