首页 > 代码库 > C++中的find,substr和getline功能详解

C++中的find,substr和getline功能详解

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
  1. void parseUrl(string &url) {
  2. stringstream ss(url); // sstream头文件
  3. string field;
  4. while(getline(ss,field,‘:‘)) {
  5. res.push_back(field);
  6. cout<<field<<endl;
  7. }
  8. string host = res[1];
  9. int pos = host.find_first_not_of(‘/‘);
  10. host = host.substr(pos,host.size()-pos);
  11. cout<<host<<endl;
  12. string port = res[2];
  13. pos = port.find_first_of(‘/‘);
  14. port = port.substr(0,pos);
  15. cout<<port<<endl;
  16. string query = res[2].substr(pos+1);
  17. pos = query.find_first_of(‘?‘);
  18. string nquery = query.substr(0,pos);
  19. cout<<nquery<<endl;
  20. string params = query.substr(pos+1);
  21. cout<<params<<endl;
  22. stringstream parass(params);
  23. while(getline(parass,field,‘&‘)) {
  24. pos = field.find_first_of(‘=‘);
  25. string key = field.substr(0,pos);
  26. string val = field.substr(pos+1);
  27. cout<<"key = "<<key<<" val = "<< val<<endl;
  28. }
  29. }

顺便提一下,C语言中也有类似的功能:如strtok和strtok_r

函数原型分别为:
   char *strtok(char *s, char *delim);
   char *strtok_r(char *str, const char *delim, char **saveptr);  线程安全版



C++中的find,substr和getline功能详解