码迷,mamicode.com
首页 > 编程语言 > 详细

随笔 | C++的替换字符串子程序

时间:2015-12-27 17:32:47      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

《C++ Primer》的一个习题,我写的时候遇到几个小问题,记录一下:

1、我以为std::string::replace只能同等长度字符串的等价替换(受C语言字符串风格的影响),事实旧字符串和新字符串是完全可以长度不一致的。

2、第一个简单的版本写出来时确实能替换成功,但有一个死循环的问题。打个比方,如果源字符串中有“Knife”,我们需要替换"K"为“KC”,就会陷入死循环。因为我用的是find找字符串,而没有设定起始寻找位置。

 

最后写上调试成功的代码。

std::string replace(const std::string& _text, const std::string& _old_replace, const std::string& _new_replace)
{
	std::string output = _text;
	std::size_t last_pos = 0;

	do
	{
		if ((last_pos = output.find(_old_replace, last_pos)) != std::string::npos)
		{
			output.replace(last_pos, _old_replace.length(), _new_replace.c_str());
			last_pos += _new_replace.length();
		}
	} while (last_pos != std::string::npos);

	return output;
}

  

随笔 | C++的替换字符串子程序

标签:

原文地址:http://www.cnblogs.com/cnmlgb/p/5080280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!