标签:
C++标准库中似乎没有分割字符串的函数。自己实现了一个,上网搜索过程中同时还发现两个比较有趣的分割方式。
1. 自己的简单实现
1 void split(const char *s, vector<string> &strs, char delim = ‘ ‘) { 2 if(s == nullptr) { 3 return; 4 } 5 6 const char *head, *tail; 7 head = tail = s; 8 9 while(*head != ‘\0‘) { 10 while(*head != ‘\0‘ && *head == delim) { 11 head++; 12 } 13 14 tail = head; 15 while(*tail != ‘\0‘ && *tail != delim) { 16 tail++; 17 } 18 19 if(head != tail) { 20 strs.push_back(string(head, tail)); 21 head = tail; 22 } else { 23 break; 24 } 25 } 26 }
将字符串s按照delim代表的字符分割,并且放入vector<string>中。
搜索过程中在stackoverflow上,发现了另外两个简单明了的办法。
2. 利用istringstream
1 int main() { 2 string sentence = "And I feel fine... asdf"; 3 istringstream iss(sentence); 4 vector<string> strs{istream_iterator<string>(iss), istream_iterator<string>()}; 5 for(auto &s: strs) { 6 cout << s << endl; 7 } 8 }
用字符串构造成字符串流,然后通过字符串流迭代器添加到vector中。
istream_iterator是使用空格进行分割的,所以这个方法的局限性就是没法使用空格以外的字符进行分割字符串
3. 利用getline函数
void split(const std::string &s, std::vector<std::string> &elems, char delim = ‘ ‘) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } } int main() { string line = "asd fasdf fadf fa"; vector<string> strs; split(line, strs); for(auto &s: strs) { cout << s << endl; } return 0; }
getline函数,顾名思义,是用来获取一行数据的,不过它的第三个参数也可以修改成其他字符,这样就可以将其他字符作为行分割符使用。
不过这种实现的缺点就是,getline每遇到一个行分割符都会返回一次,所以对于分割符连续的情况就束手无策了。
例如:
1 string line = "asd fasdf fadf fa";
打印结果就是:
asd
fasdf
fadf
fa
标签:
原文地址:http://www.cnblogs.com/fanux/p/5958378.html