标准库中的string是没有此函数的,但我们可以试着实现它。
借鉴网上的函数如下
- list<string> util::split(string str, string separator)
- {
- list<string> result;
- int cutAt;
- while( (cutAt = str.find_first_of(separator)) != str.npos )
- {
- if(cutAt > 0)
- {
- result.push_back(str.substr(0, cutAt));
- }else{
- result.push_back("");
- }
- str = str.substr(cutAt + 1);
- }
- if(str.length() > 0)
- {
- result.push_back(str);
- }else{
- result.push_back("");
- }
- return result;
- }
这样有个问题就是添加了“”,有时我们不需要,可以去掉它。
- list<string> util::split(string str, string separator)
- {
- list<string> result;
- int cutAt;
- while( (cutAt = str.find_first_of(separator)) != str.npos )
- {
- if(cutAt > 0)
- {
- result.push_back(str.substr(0, cutAt));
- }
- str = str.substr(cutAt + 1);
- }
- if(str.length() > 0)
- {
- result.push_back(str);
- }
- return result;
- }