字符串分割split_string:用vector和string容器实现
当返回值是一个数组时,不妨采用vector类。
split_string的demo程序:
1 #include<iostream>
2 using namespace std;
3 #include<string>
4 #include<vector>
5
6 vector<string> split_string(const string& s,const char* del)
7 {
8 size_t pos=0,pre_pos=0;
9 vector<string> tmp;
10 while( (pos = s.find(del,pre_pos))!= string::npos)
11 {
12 tmp.push_back(s.substr(pre_pos,pos-pre_pos));
13 pre_pos = ++pos;
14 }
15 if(pre_pos != s.size()) tmp.push_back(s.substr(pre_pos,s.size()-pre_pos));
16 return tmp;
17 }
18
19 int main(int argc,char**argv)
20 {
21
22 string s = "how are you?";
23 char * del = " ";
24 vector<string> tmp = split_string(s,del);
25 cout<<tmp.size()<<endl; //输出分割的段数
26 for(size_t i=0;i < tmp.size();++i)
27 cout<<tmp[i]<<endl; //输出分割后的子串
28
29 cin.get();
30 return 0;
31 }
*****Men Pass Away But Their Deeds Abide.*****

浙公网安备 33010602011771号