C++標准庫里面沒有像java的String類中提供的字符分割函數split ,着實不方便。
1.簡潔高效的方法(不過只能包含一個分隔符):
1 #include <vector> 2 #include <string> 3 #include <iostream> 4 using namespace std; 5 6 void SplitString(const string& s, vector<string>& v, const string& c) 7 { 8 string::size_type pos1, pos2; 9 pos2 = s.find(c); 10 pos1 = 0; 11 while(string::npos != pos2) 12 { 13 v.push_back(s.substr(pos1, pos2-pos1)); 14 15 pos1 = pos2 + c.size(); 16 pos2 = s.find(c, pos1); 17 } 18 if(pos1 != s.length()) 19 v.push_back(s.substr(pos1)); 20 } 21 22 int main(){ 23 string s = "a,b,c,d,e,f"; 24 vector<string> v; 25 SplitString(s, v,","); //可按多個字符來分隔; 26 for(vector<string>::size_type i = 0; i != v.size(); ++i) 27 cout << v[i] << " "; 28 cout << endl; 29 //輸出: a b c d e f 30 }
當處理有空格的字符串時,還是很有用的!!
2.可包含多個分隔符的實現方式
1 #include <vector> 2 #include <string> 3 #include <iostream> 4 using namespace std; 5 6 vector<string> split(const string &s, const string &seperator){ 7 vector<string> result; 8 typedef string::size_type string_size; 9 string_size i = 0; 10 11 while(i != s.size()){ 12 //找到字符串中首個不等於分隔符的字母; 13 int flag = 0; 14 while(i != s.size() && flag == 0){ 15 flag = 1; 16 for(string_size x = 0; x < seperator.size(); ++x) 17 if(s[i] == seperator[x]){ 18 ++i; 19 flag = 0; 20 break; 21 } 22 } 23 24 //找到又一個分隔符,將兩個分隔符之間的字符串取出; 25 flag = 0; 26 string_size j = i; 27 while(j != s.size() && flag == 0){ 28 for(string_size x = 0; x < seperator.size(); ++x) 29 if(s[j] == seperator[x]){ 30 flag = 1; 31 break; 32 } 33 if(flag == 0) 34 ++j; 35 } 36 if(i != j){ 37 result.push_back(s.substr(i, j-i)); 38 i = j; 39 } 40 } 41 return result; 42 } 43 44 int main(){ 45 // string s = "a,b*c*d,e"; 46 string s; 47 getline(cin,s); 48 vector<string> v = split(s, ",*"); //可按多個字符來分隔; 49 for(vector<string>::size_type i = 0; i != v.size(); ++i) 50 cout << v[i] << " "; 51 cout << endl; 52 //輸出: a b c d e 53 }
3.用C語言中的strtok 函數來進行分割
1 #include <string.h> 2 #include <stdio.h> 3 4 int main(){ 5 char s[] = "a,b*c,d"; 6 const char *sep = ",*"; //可按多個字符來分割 7 char *p; 8 p = strtok(s, sep); 9 while(p){ 10 printf("%s ", p); 11 p = strtok(NULL, sep); 12 } 13 printf("\n"); 14 return 0; 15 } 16 //輸出: a b c d
參考博客:C++中String類的字符串分割實現