C++ 字符串分割,
//s为原始字符串,v为分割后的字符串数组,c为分割字符串如(,:,;)
splitString(const std::string& s, std::vector<std::string>& v, const std::string& c)
{
std::string::size_type pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while (std::string::npos != pos2)
{
v.push_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if (pos1 != s.length())
v.push_back(s.substr(pos1));
}
示例,将string str="1,2,3,4,5" 按逗号分割
int main()
{
string str="1,2,3,4,5";
vector<string> strs;
splitString(str,strs,",");
for(auto item:strs)
cout<<item<<endl;
}