這裏是我找到字符串中的序列,並與另一個替換它的代碼:單引號++的問題查找和替換功能
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;
}
我希望這可以幫助有同樣的問題一些人。
嗯,任何原因downvote?沒有正當理由的下降是無用的,因爲他們不告訴創作者如何改進他們的問題。 – 2009-07-06 16:04:54