The use of string cutting is still very high, string itself does not provide a method of cutting, but can be implemented using the package provided by the STL or by the C function strtok () function.
1, through the STL implementation
Two functions involving the string class find and substr:
1. Find function
Prototype: size_t find (const string& str, size_t pos = 0) const;
Function: Finds the position where the substring first appears.
Parameter description: STR is a substring and POS is the initial find location.
Return value: If found, returns the first occurrence of the position, otherwise returns String::npos
2. substr function
Prototype: String substr (size_t pos = 0, size_t n = npos) const;
function: Gets substring.
Parameter description: POS is the starting position (default is 0), n is the end position (default is NPOs)
return value: substring
Std::vector<std::string> splitwithstl (const std::string &str,const std::string &pattern) { std:: Vector<std::string> Resvec; if ("" = = str) { return resvec; } Convenient interception of the last piece of data std::string STRs = str + pattern; size_t pos = strs.find (pattern); size_t size = Strs.size (); while (pos! = Std::string::npos) { std::string x = strs.substr (0,pos); Resvec.push_back (x); STRs = Strs.substr (pos+1,size); pos = Strs.find (pattern); } return Resvec;}
2, by using the Strtok () function to achieve
prototype : Char *strtok (char *str, const char *delim);
Function: Decomposes a string into a set of strings. S is the string to be decomposed, Delim is the delimiter string.
description : Strtok () is used to split a string into fragments. The parameter S points to the string to be split, the parameter Delim is the split string, and when Strtok () discovers the split character of the parameter Delim in the string of the parameter s, the character is changed to the \ = character. At the first call, Strtok () must give the parameter S string, and the subsequent call sets the parameter s to null. Each successful call returns a pointer to the fragment being split.
Other: strtok function thread is unsafe, you can use Strtok_r instead.
The code is as follows:
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;}
Two methods of C + + split string