The frequency of string cutting is still quite high. The string itself does not provide a cutting method, but it can be implemented using the package provided by stl or through the c function strtok() function.
1. Implemented through stl
Two functions of the string class, find and substr, are involved:
1. The prototype of the find function
: size_t find ( const string& str, size_t pos = 0 ) const;
Function: Find the first occurrence of a substring.
Parameter description: str is a substring, and pos is the initial search position.
Return value: if found, return the position of the first occurrence, otherwise return string::npos
2. Substr function
prototype: string substr ( size_t pos = 0, size_t n = npos ) const;
Function: Get the substring.
Parameter description: pos is the start position (default is 0), n is the end position (default is npos)
Return value: The substring
code is as follows:
1 std::vector<std:: string > splitWithStl( const std:: string &str, const std:: string & pattern) 2 { 3 std::vector<std:: string > resVec; 4 5 if ( "" = = str) 6 { 7 return resVec; 8 } 9 // Convenient to intercept the last piece of data 10 std:: string strs = str + pattern; 11 12 size_t pos = strs.find(pattern); 13 size_t size = strs.size(); 14 15 while (pos != std::string::npos) 16 { 17 std::string x = strs.substr(0,pos); 18 resVec.push_back(x); 19 strs = strs.substr(pos+1,size); 20 pos = strs.find(pattern); 21 } 22 23 return resVec; 24 }
2. By using strtok() function
原型:char *strtok(char *str, const char *delim);
功能:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
描述:strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时 则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。
其它:strtok函数线程不安全,可以使用strtok_r替代。
代码如下:
vector<string> split(const string &str,const string &pattern) { //const char* convert to char* char * strc = new char[strlen(str.c_str())+1]; strcpy(strc, str.c_str()); vector<string> resultVec; char* tmpStr = strtok(strc, pattern.c_str()); while (tmpStr != NULL) { resultVec.push_back(string(tmpStr)); tmpStr = strtok(NULL, pattern.c_str()); } delete[] strc; return resultVec; }