1. 程式人生 > >STL std::string 字元全域性替換

STL std::string 字元全域性替換

 由於stl string 沒有提供字元全域性替換功能所以用起來還不是很方便 所以博主今天就把此功能單獨寫了一個方法提供使用

/*
 *    函式:
 *         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:", ":","::");

以上方法會出現死迴圈效果建議採用下面最新的實現:

修正死迴圈程式碼實現如下:↓


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 
版權宣告:本文為博主原創文章,轉載請