今天想要在一个字符串中按照特定子串分割字符串,但是发现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;
}
}