C++ 按照字符串子串分割字符串 boost

今天想要在一个字符串中按照特定子串分割字符串,但是发现boost::split 只能分割单个字符,string类也没有相关的方法。 于是结合string::find 和 string::sub_str 实现了对任意字符串的任意子串的分割,不限制子串位置和长度,但子串长度不能大于源串。

方法源码:

/**********************************************************************************************************
 @ 功能:按照字符串分割字符串
 @ 参数:[I] :源串, 分割的字符串 
		 [O] :string 容器
@ 返回:-1 参数错误 0正常
@ 备注:
*********************************************************************************************************/
int SplitStr(string str, string sp, vector<string>& vstr)
{
	string nextcontent = str;
	int local = 0;
	if (sp == "" || str == "" || sp.length() > str.length())
	{
		return -1;
	}

	while (1) {
		local = nextcontent.find(sp);
		if (local == string::npos)
		{
			break;
		}
	    
		string temp = nextcontent.substr(0, local);
		if (temp != "")
		{
			vstr.push_back(temp);
		}
		nextcontent = nextcontent.substr(local + sp.length(), nextcontent.length());
	 
	}
	if (nextcontent != "") {
		vstr.push_back(nextcontent);
	}
	return 0;
}

使用:

	string userdata = "S1234AABBCCS1234e2d3c91d1S12359S1232791d16761S123"; 
	string sp = "S123"; 
	vector<string> split;

	if (0 == SplitStr(userdata, sp, split)) {
		for (vector<string>::iterator it = split.begin(); it != split.end();it++)
		{
			cout << *it << " . " << endl;
		}
	}

运行效果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值