C++中处理split的函数,首先要了解几个函数
C++中string自己带的find_first_of 或者find_first_not_of
find_last_of 或者find_last_not_of
函数原型为:可以用来超找字符串,char,char *三种类型
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; |
其次string中的substr函数,根据上述得到的位置,然后调用substr函数可以截取到制定区间内的字符串,如果len未指定,则直接到尾部;
string substr (size_t pos = 0, size_t len = npos) const; 用find和substr可以实现getline的分词功能,以前只以为是读字符串,该功能可以按照指定的分隔符进行读取字符串流;
istream& getline (istream& is, string& str, char delim)
istream& getline (istream& is, string& str); 实现parse url: 代码:url 为 http://www.baidu.com:80/query?k1=v1&k2=v2
- void parseUrl(string &url) {
- stringstream ss(url); // sstream头文件
- 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<<host<<endl;
- 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;
- }
- }
顺便提一下,C语言中也有类似的功能:如strtok和strtok_r 函数原型分别为:
char *strtok(char *s, char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr); 线程安全版
时间: 2024-11-16 17:40:18