The function of split in C + + is first to understand several functions
Find_first_of or find_first_not_of in C + + with string itself
Find_last_of or Find_last_not_of
Function prototype: can be used to search for strings, Char,char * Three types
String (1) |
size_t find_first_of (const string& str, size_t pos = 0) const; |
C-string (2) |
size_t find_first_of (const char* s, size_t pos = 0) const; |
Buffer (3) |
size_t find_first_of (const char* S, size_t pos, size_t N) const; |
Character (4) |
size_t find_first_of (char c, size_t pos = 0) const; |
Secondly, the SUBSTR function in string, according to the position obtained above, and then call the SUBSTR function can intercept the string within the set interval, if Len is not specified, then directly to the tail;
String substr (size_t pos = 0, size_t len = npos) const;
With find and substr can be implemented Getline word segmentation function, previously only thought to be a read string, the function can follow the specified delimiter to read the string stream;
istream& Getline (istream& is, string& str, char Delim)
istream& Getline (istream& is, string& str);
To implement the parse URL:
Code: URL is http://www.baidu.com:80/query?k1=v1&k2=v2
- void parseURL (String &url) {
- StringStream SS (URL); Sstream header File
- String field;
- while (Getline (Ss,field, ': ')) {
- Res.push_back (field);
- cout<<field<<endl;
- }
- String host = Res[1];
- int pos = host.find_first_not_of ('/');
- Host = Host.substr (Pos,host.size ()-pos);
- cout<
- String port = res[2];
- pos = port.find_first_of ('/');
- Port = port.substr (0,pos);
- cout<<port<<endl;
- string query = Res[2].substr (pos+1);
- pos = query.find_first_of ('? ');
- String nquery = Query.substr (0,pos);
- cout<<nquery<<endl;
- string params = Query.substr (pos+1);
- cout<<params<<endl;
- StringStream Parass (params);
- while (Getline (Parass,field, ' & ')) {
- pos = field.find_first_of (' = ');
- String key = Field.substr (0,pos);
- String val = Field.substr (pos+1);
- cout<< "key =" <<key<< "val =" << val<<endl;
- }
- }
By the way, there are similar features in the C language: Strtok and Strtok_r, for example.
The function prototypes were:
Char *strtok (char *s, char *delim);Char *strtok_r (char *
Str, const char *
Delim, char * *
saveptr); Thread-Safe Edition
Find,substr and Getline features in C + +