基于C++字符串替換函數(shù)的使用詳解
更新時(shí)間:2013年05月17日 17:49:50 作者:
本篇文章是對(duì)C++字符串替換函數(shù)的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
在C++中,字符串替換有很多方法,這里主要說(shuō)一下STL里的WString中的替換,雖然WString自帶了一個(gè)Replace函數(shù),但是只能替換一次,太不好了,因此單獨(dú)寫(xiě)了個(gè)替換函數(shù)
[函數(shù)]
/**
* @brief 實(shí)現(xiàn)字符串替換
* @param orignStr 源串
* @param oldStr 查找的串
* @param newStr 替換的新串
* @return 返回修改后的串
*/
static wstring Replace(const wstring& orignStr, const wstring& oldStr, const wstring& newStr);
[實(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 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 實(shí)現(xiàn)字符串替換
* @param orignStr 源串
* @param oldStr 查找的串
* @param newStr 替換的新串
* @return 返回修改后的串
*/
static wstring Replace(const wstring& orignStr, const wstring& oldStr, const wstring& newStr);
[實(shí)現(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)文章
C++ STL入門(mén)教程(1) vector向量容器使用方法
這篇文章主要為大家詳細(xì)介紹了C++ STL入門(mén)教程第一篇,vector向量容器使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
如何優(yōu)雅地使用c語(yǔ)言編寫(xiě)爬蟲(chóng)
如何優(yōu)雅地使用c語(yǔ)言編寫(xiě)爬蟲(chóng),本文介紹cspider爬蟲(chóng)庫(kù),這個(gè)cspider爬蟲(chóng)庫(kù)的使命在于,我們能夠使用c語(yǔ)言,依然能夠優(yōu)雅地編寫(xiě)爬蟲(chóng)程序,需要的朋友可以參考下2015-12-12
關(guān)于C++函數(shù)模版的實(shí)現(xiàn)講解
今天小編就為大家分享一篇關(guān)于關(guān)于C++函數(shù)模版的實(shí)現(xiàn)講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
詳解如何使用openssl創(chuàng)建自簽名證書(shū)
這篇文章主要為大家介紹了詳解如何使用openssl創(chuàng)建自簽名證書(shū)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

