(适用于一个分隔符)
//vector
vector<string> Split(string &s, string &c)
{
vector<string>v;
int pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while (true)
{
if (pos1==s.length()-1)
{
break;
}
v.push_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + 1;
pos2 = s.find(c, pos1);
}
v.push_back(s.substr(pos1));
return v;
}
int main() {
string s = "3 4 + 2 / 5";
string c = " ";
vector<string> v;
v = Split(s, c); //可按多个字符来分隔;
for (int i = 0; i < v.size(); i++)
cout << v[i] << ",";
cout << endl;
//输出: a b c d e f
system("pause");
return 0;
}
//list
list<string> Split(string &s, string &c)
{
list<string>list;
int pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while (true)
{
if (pos1 == s.length() - 1)
{
break;
}
list.push_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + 1;
pos2 = s.find(c, pos1);
}
list.push_back(s.substr(pos1));
return list;
}
int main() {
string s = "3 4 + 2 / 5 +";
string c = " ";
list<string> l;
l = Split(s, c); //可按多个字符来分隔;
for (list<string>::iterator it = l.begin(); it != l.end(); it++)
{
cout << *it << ",";
}
cout << endl;
//输出: a b c d e f
system("pause");
return 0;
}