在C++中,字符串替換有很多方法,這里主要說一下STL里的WString中的替換,雖然WString自帶了一個Replace函數,但是只能替換一次,太不好了,因此單獨寫了個替換函數
[函數]
?
/**
??????? * @brief?? 實現字符串替換
??????? * @param?? orignStr 源串
??????? * @param?? oldStr? 查找的串
??????? * @param?? newStr? 替換的新串
??????? * @return? 返回修改后的串
??????? */
??????? static wstring Replace(const wstring& orignStr, const wstring& oldStr, const wstring& newStr);
[實現]
?
?
?
std::wstring Replace( const wstring& orignStr, const wstring& oldStr, const wstring& newStr )
{
??? size_t pos = 0;
??? wstring tempStr = orignStr;
??? wstring::size_type newStrLen = newStr.length();
??? wstring::size_type oldStrLen = oldStr.length();
??? while(true)
??? {
??????? pos = tempStr.find(oldStr, pos);
??????? if (pos == wstring::npos) break;
??????? tempStr.replace(pos, oldStrLen, newStr);????????
??????? pos += newStrLen;
??? }
??? return tempStr;
}
到這里,C++字符串替換函數的使用詳解就全部講完了。如果有什么不清楚可以留言給我。如果覺得我寫得不錯的話,請給武林技術頻道一個關注,謝謝!