用c++实现string split
以前做php网站后台的时候经常会用到这个函数,感觉还是挺好用的;最近在做一个c++项目的时候,刚好需要用到这个函数,而c++没有提供,只好自己写一个了~~
代码:
1 /** 2 * String split. 3 */ 4 std::vector<std::string> &split(std::string src, std::vector<std::string> &dst, std::string &delim) 5 { 6 size_t last = 0; 7 size_t index = src.find_first_of(delim, last); 8 9 while (index != std::string::npos) 10 { 11 dst.push_back(src.substr(last, index - last)); 12 last = src.find_first_not_of(delim, index + 1); 13 index = src.find_first_of(delim, last); 14 } 15 16 if (index-last > 0) 17 { 18 dst.push_back(src.substr(last, index - last)); 19 } 20 21 return dst; 22 } 23 24 std::vector<std::string> &split(std::string src, std::vector<std::string> &dst) 25 { 26 std::string delim(" \t"); 27 return split(src, dst, delim); 28 }
浙公网安备 33010602011771号