忘记在哪看到的了,split不是原创
vector<string> split(const string &ComStr, const string &pattern)//字符串分割
{
vector<string> res;
if(ComStr == "")
return res;
//在字符串末尾也加入分隔符,方便截取最后一段
string strs = ComStr + pattern;
size_t pos = strs.find(pattern);
while(pos != strs.npos)
{
string temp = strs.substr(0, pos);
res.push_back(temp);
//去掉已分割的字符串,在剩下的字符串中进行分割
strs = strs.substr(pos+1, strs.size());
pos = strs.find(pattern);
}
return res;
}
使用示例
将字符串按“,”拆分,并将拆分的string数组转成int数组,
int ToInt(const string &ComStr)
{
return atoi(ComStr.c_str()); //将String类型转成int类型
}
//(*i).fd_Expectation:"2,3,4,5"
vector <string> exp=split((*i).fd_Expectation,",");//拆分期望值
vector <int> expt;
transform(exp.begin(), exp.end(), back_inserter(expt), ToInt);
//vector,string->vector.int