针对 std::string 的 trim 和 replace 方法

std::string不支持trim方法,同时原生的replace方法在使用上和其它语言也有些许差别,这里提供了两个替代方法,个人感觉更加好用。std::wstring等类似。

static int(__cdecl is_space)(int const c)
{
	return (c >= -127 && c <= 127 && isspace(c) != 0);
}

//-------------------------------------------------------------------------

static void trim(std::string &s)
{
	// trim from start (in place)
	s.erase(s.begin(), std::find_if(s.begin(), s.end(),
									std::not1(std::ptr_fun<int, int>(is_space))));
	// trim from end (in place)
	s.erase(std::find_if(s.rbegin(), s.rend(),
						 std::not1(std::ptr_fun<int, int>(is_space))).base(), s.end());
}

//-------------------------------------------------------------------------

static void replace(std::string &s, 
					const char *p1, int l1,
					const char *p2, int l2)
{
	std::string::size_type pos = 0;
	while ((pos = s.find(p1, pos)) != std::string::npos) {
		s.replace(pos, l1, p2);
		pos = pos + l2;
	}
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值