2016-11-22 172 views
-2

我如何查找和替換(匹配整個單詞)。 我有這個。C++查找和替換整個單詞

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(); 
    } 
} 

但它dosnt搜索整個詞。 例如,如果我嘗試

string test = "i like cake"; 
ReplaceString(test, "cak", "notcake"); 

它仍然會取代,但我希望它全字匹配。

+4

真的嗎?你不能先搜索?今天發佈了三個相關問題。我強烈建議與你的同學談談。 –

+2

[用另一個字符串替換字符串的一部分]可能的重複(http://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string) – Hcorg

+0

@Hcorg看着那個,它看起來像是這個作者寫了完全相同的功能,或者已經嘗試過那個(因爲這兩個樣本在功能上是相同的,只有不同的參數名稱)。 – lcs

回答

1

你只是盲目地將search的任何實例替換爲replace而不檢查在執行替換之前它們是否是全部單詞。

這裏只是一對夫婦的事情,你可以嘗試解決的是:

  • 分割字符串爲單個單詞,然後檢查每個單詞對search,並在必要時更換。然後重建該字符串。
  • 只有在pos-1pos + search.length() + 1都是空格時才能替換。
-1

正則表達式解決方案,如果你有機會獲得C++編譯器11:

#include <iostream> 
#include <string> 
#include <regex> 

void ReplaceString(std::string &subject, const std::string& search, const std::string& replace) 
{ 
    // Regular expression to match words beginning with 'search' 
    std::regex e ("(\\b("+search+"))([^,. ]*)"); 
    subject = std::regex_replace(subject,e,replace) ; 
} 

int main() 
{ 
    // String to search within and do replacement 
    std::string s ("Cakemoney, cak, cake, thecakeisalie, cake.\n"); 
    // String you want to find and replace 
    std::string find ("cak") ; 
    // String you want to replace with 
    std::string replace("notcake") ; 

    ReplaceString(s, find, replace) ; 

    std::cout << s << std::endl; 

    return 0 ; 
} 

輸出: Cakemoney,notcake,notcake,thecakeisalie,notcake。

有關正則表達式字符串的更多信息(\\b("+search+"))([^,. ]*)。需要注意的是更換search後,這個字符串將是: (\\b(cak))([^,. ]*)

  • \ B(CAK) - 匹配單詞,CAK開始不管會發生什麼後
  • ([^,...] *) - 匹配任何東西最多,.(空格)。

以上基本上只是撕掉example provided here。答案是區分大小寫的,並且還將替換^之後列出的三個之外的標點符號,但請隨時瞭解有關正則表達式的更多信息以制定更一般的解決方案。