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;
}




  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值