C++字符串替換函數(shù)具體實(shí)現(xiàn)方法詳解
作者:佚名
我們?cè)趯?shí)際編程中,如果沒有現(xiàn)成的函數(shù),可以自行編寫一個(gè)C++函數(shù)來實(shí)現(xiàn)具體的功能。今天就為大家詳細(xì)介紹一下C++字符串替換函數(shù)的實(shí)現(xiàn)方式。
C++編程語言應(yīng)方式靈活,一個(gè)功能的實(shí)現(xiàn)可以采用多種方式來實(shí)現(xiàn)。比如對(duì)于字符串替換就可以有很多方法來實(shí)現(xiàn),這里主要說一下STL里的WString中的替換,雖然WString自帶了一個(gè)Replace函數(shù),但是只能替換一次,太不好了,因此單獨(dú)寫了個(gè)C++字符串替換函數(shù)
C++字符串替換函數(shù)代碼如下:
- @brief 實(shí)現(xiàn)字符串替換
- @param orignStr 源串
- @param oldStr 查找的串
- @param newStr 替換的新串
- @return 返回修改后的串
- static wstring Replace(const wstring& orignStr,
const wstring& oldStr, const wstring& newStr);
[C++字符串替換函數(shù)的實(shí)現(xiàn)]
- std::wstring Replace( const wstring& orignStr, const
wstring& oldStr, const wstring& newStr )- {
- size_t pos = 0;
- wstring tempStr = orignStr;
- wstring::size_type newStrnewStrLen = newStr.length();
- wstring::size_type oldStroldStrLen = oldStr.length();
- while(true)
- {
- pos = tempStr.find(oldStr, pos);
- if (pos == wstring::npos) break;
- tempStr.replace(pos, oldStrLen, newStr);
- pos += newStrLen;
- }
- return tempStr;
- }
以上就是我們對(duì)C++字符串替換函數(shù)的相關(guān)介紹。
【編輯推薦】
責(zé)任編輯:曹凱
來源:
博客園