2009-07-06 39 views
1

這裏是我找到字符串中的序列,並與另一個替換它的代碼:單引號++的問題查找和替換功能

std::string find_and_replace(string &source, string find, string replace) 
{ 
    size_t j; 
    for (; (j = source.find(find)) != string::npos ;) 
    { 
     source.replace(j, find.length(), replace); 
    } 
    return source; 
} 

一切正常,當我打電話是這樣的:

find_and_replace(test, "foo", "bar") 

我的申請要求我用兩個單引號替換單引號,而不是雙引號。例如,我會打電話:

find_and_replace(test, "'", "''") 

但是每當我調用此函數時,函數都會因某種原因而凍結。有誰知道可能是什麼原因造成這個問題?

編輯:基於我已經得到了答案,我有固定的代碼:

std::string find_and_replace(string &source, string find, string replace) 
{ 
    string::size_type pos = 0; 
    while ((pos = source.find(find, pos)) != string::npos) { 
     source.replace(pos, find.size(), replace); 
     pos += replace.size(); 
    } 
    return source; 
} 

我希望這可以幫助有同樣的問題一些人。

+0

嗯,任何原因downvote?沒有正當理由的下降是無用的,因爲他們不告訴創作者如何改進他們的問題。 – 2009-07-06 16:04:54

回答

9

你有一個無限循環,因爲你的情況不會前進。你總是運行j = source.find(find),但是你用''代替',所以你總是每次都找到第一個撇號,併爲該字符串添加一個新的撇號。

您需要確保在每次替換某些東西時移動要向前掃描的位置,以避免兩次匹配相同的撇號。

find函數接受第二個參數,該參數是字符串中用於查找子字符串的起始位置。一旦找到第一個匹配的位置,將起始位置移動到該位置加上要替換的字符串的長度。

4

因爲你用''替換',然後再次搜索',找到你剛剛放在那裏的第一個。你替換哪個。等等。

1

您試圖替換您添加的相同字符串。

1

從右向左工作可能會更好。這適用於我:

const std::string& replacestring(std::string& strString, const std::string& strOld, const std::string& strNew) 
{ 
    for (int nReplace = strString.rfind(strOld); nReplace != std::string::npos; nReplace = strString.rfind(strOld, nReplace - 1)) 
    { 
     strString.replace(nReplace, strOld.length(), strNew); 
     if (nReplace == 0) 
      break; 
    } 
    return strString; 
} 
+0

從右到左沒有區別,除非意外。 – 2009-07-06 14:12:45