Standard string: /*************************************** * *** the tokenize function for STD:: string *************************************** * *****/# include <string> # include <vector> # include <iostream> using namespace STD; typedef basic_string <char >:: size_type S_T; static const S_T NPOs =-1; // trim indicates whether to retain empty strings. The default value is retained. Vector <string> tokenize (const string & SRC, string Tok, bool trim = false, string null_subst = "") {If (SRC. empty () | Tok. empty () throw "tokenize: empty string \ 0"; vector <string> V; S_T pre_index = 0, Index = 0, Len = 0; while (Index = SRC. find_first_of (Tok, pre_index ))! = NPOs) {If (LEN = index-pre_index )! = 0) v. push_back (SRC. substr (pre_index, Len); else if (TRIM = false) v. push_back (null_subst); pre_index = index + 1;} string endstr = SRC. substr (pre_index); If (TRIM = false) v. push_back (endstr. empty ()? Null_subst: endstr); else if (! Endstr. empty () v. push_back (endstr); Return v ;}/// use a complete string of delimit (rather than a character in it) to separate the SRC string. If trim is not selected, it is strictly separated. Vector <string> split (const string & SRC, string delimit, string null_subst = "") {If (SRC. empty () | delimit. empty () throw "split: empty string \ 0"; vector <string> V; S_T deli_len = delimit. size (); long Index = NPOs, last_search_position = 0; while (Index = SRC. find (delimit, last_search_position ))! = NPOs) {If (Index = last_search_position) v. push_back (null_subst); elsev. push_back (SRC. substr (last_search_position, index-last_search_position); last_search_position = index + deli_len;} string last_one = SRC. substr (last_search_position); V. push_back (last_one.empty ()? Null_subst: last_one); Return v ;}// testint main (void) {string src = ", AB, CDE;, FG,"; string Tok = ",; "; vector <string> V1 = tokenize (SRC, Tok, true); vector <string> v2 = tokenize (SRC, Tok, false," <null> "); cout <"------------- V1:" <Endl; For (INT I = 0; I <v1.size (); I ++) {cout <V1 [I]. c_str () <Endl ;}cout <"------------- V2:" <Endl; For (Int J = 0; j <v2.size (); j ++) {cout <V2 [J]. c_str () <Endl ;} try {string S = "###### 123 #4 ### 56 ####### 789 ###"; string del = ""; // "###"; vector <string> V3 = Split (S, Del, "<null>"); cout <"----------- v3:" <Endl; for (int K = 0; k <v3.size (); k ++) {cout <V3 [K]. c_str () <Endl ;}catch (char * s) {cout <S <Endl ;}return 0 ;}
Reference: http://hi.baidu.com/ztianl/blog/item/122b46453062e43a8694737d.html