基于C++字符串替換函數(shù)的使用詳解
更新時間:2013年05月17日 17:49:50 作者:
本篇文章是對C++字符串替換函數(shù)的使用進行了詳細的分析介紹,需要的朋友參考下
在C++中,字符串替換有很多方法,這里主要說一下STL里的WString中的替換,雖然WString自帶了一個Replace函數(shù),但是只能替換一次,太不好了,因此單獨寫了個替換函數(shù)
[函數(shù)]
/**
* @brief 實現(xiàn)字符串替換
* @param orignStr 源串
* @param oldStr 查找的串
* @param newStr 替換的新串
* @return 返回修改后的串
*/
static wstring Replace(const wstring& orignStr, const wstring& oldStr, const wstring& newStr);
[實現(xiàn)]
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;
}
[函數(shù)]
復(fù)制代碼 代碼如下:
/**
* @brief 實現(xiàn)字符串替換
* @param orignStr 源串
* @param oldStr 查找的串
* @param newStr 替換的新串
* @return 返回修改后的串
*/
static wstring Replace(const wstring& orignStr, const wstring& oldStr, const wstring& newStr);
[實現(xiàn)]
復(fù)制代碼 代碼如下:
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;
}
相關(guān)文章
關(guān)于C++函數(shù)模版的實現(xiàn)講解
今天小編就為大家分享一篇關(guān)于關(guān)于C++函數(shù)模版的實現(xiàn)講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12

