std::string 字符串split的操作(仿造python代码)

在字符串操作中,常常遇到按照某个字符将字符串按照某种方式(逗号,空格等等)分割成很多子字符串。在python中会经常遇到,对于项目中也常常用到。C++没有专门的函数,需要实现一下这个功能如下:
参见源码:

void split(std::vector<std::string>& split_strs, std::string const& str, char delim = ' ', bool keep_empty = false)
{
	std::size_t new_tok = 0;
	std::size_t cur_pos = 0;
	for (; cur_pos < str.size(); ++cur_pos)
	{
		if (str[cur_pos] == delim)
		{
			std::string token = str.substr(new_tok, cur_pos - new_tok);
			if (keep_empty || !token.empty())
				split_strs.push_back(token);
			new_tok = cur_pos + 1;
		}
	}

	if (keep_empty || new_tok < str.size())
		split_strs.push_back(str.substr(new_tok));
}

这份代码,将str字符串,按照delim的方式分割成多个字符串,然后存入split_strs,用于后续操作。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值