STL std::string 字符全局替換

 因爲stl string 沒有提供字符全局替換功能因此用起來還不是很方便 因此博主今天就把此功能單獨寫了一個方法提供使用app

/*
 *    函數:
 *         replace(替換字符串)
 *  參數:
 *        pszSrc:源字符串
 *        pszOld:須要替換的字符串
 *        pszNew:新字符串
 *  返回值:
 *        返回替換後的字符串
 *    備註:
 *    須要添加#include <string>頭文件
 * ssdwujianhua 2017/08/30 
 */
static std::string replace(const char *pszSrc, const char *pszOld, const char *pszNew)
{
    std::string strContent, strTemp;
    strContent.assign( pszSrc );
    while( true )
    {
        std::string::size_type nPos = 0;
        nPos = strContent.find(pszOld, nPos);
        strTemp = strContent.substr(nPos+strlen(pszOld), strContent.length());
        if ( nPos == std::string::npos )
        {
            break;
        }
        strContent.replace(nPos,strContent.length(), pszNew );
        strContent.append(strTemp);
    }
    return strContent;
}
以上出現死循環效果例子:replace("dfjadjdfja:", ":","::");函數

以上方法會出現死循環效果建議採用下面最新的實現:.net

修正死循環代碼實現以下:↓blog


static std::string replace(const char *pszSrc, const char *pszOld, const char *pszNew)
{
    std::string strContent, strTemp;
    strContent.assign( pszSrc );
    std::string::size_type nPos = 0;
    while( true )
    {
        nPos = strContent.find(pszOld, nPos);
        strTemp = strContent.substr(nPos+strlen(pszOld), strContent.length());
        if ( nPos == std::string::npos )
        {
            break;
        }
        strContent.replace(nPos,strContent.length(), pszNew );
        strContent.append(strTemp);
        nPos +=strlen(pszNew) - strlen(pszOld)+1; //防止重複替換 避免死循環
    }
    return strContent;
}字符串

--------------------- 
做者:wu110112 
來源:CSDN 
原文:https://blog.csdn.net/wu110112/article/details/78750623 
版權聲明:本文爲博主原創文章,轉載請附上博文連接!string

相關文章
相關標籤/搜索