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(" "); 14 return 0; 15 } 16 //输出: a b c d
参考博客:C++中String类的字符串分割实现