分割字符串(字符串的split)

C style:

 

#include <stdio.h> #include <string.h> int main(void) { char str[] = "a,b,c*d"; const char * split = ",*"; char *p; p = strtok(str, split); while (p != NULL) { printf("%s/n", p); p = strtok(NULL, split); } return 0; }

C++ style(只考虑空格):

#include <iostream> #include <sstream> #include <iterator> #include <vector> using namespace std; void split(string str, vector<string> & list) { istringstream ss(str); string t; while (ss >> t) { list.push_back(t); } } int main() { string str = "a b c"; vector<string> v; split(str, v); copy(v.begin(), v.end(), ostream_iterator<string>(cout, "/n")); return 0; }

C++版:

#include <iostream> #include <sstream> #include <string> using namespace std; int main() { string token; string line("a:b:c:d"); stringstream iss; iss << line; while (getline(iss,token, ':')) cout << token << endl; return 0; }

注意getline和cin.getline的区别:getline是针对string的,而cin.getline是针对char的。

 

C++自己写算法版:

#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int main() { string str = "a:b:c"; vector<string> list; int p1 = 0, p2; while ((p2 = str.find(':', p1)) != string::npos) { list.push_back(str.substr(p1, p2 - p1)); p1 = p2 + 1; } list.push_back(str.substr(p1, str.length() - p1)); copy(list.begin(), list.end(), ostream_iterator<string>(cout, "/n")); return 0; }

 

STL版:

vector<string> tokens; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(tokens));

你可能感兴趣的:(c,算法,String,list,null,token)