C++ splits the string according to a specific separator-implementation

Method 1. Use the built-in functions of the string class

The code of this method is as follows:

void stringToken(const string sToBeToken, const string sSeperator, vector<string>& vToken)
{
    
    
    string sCopy = sToBeToken;
    int iPosEnd = 0;
    while (true)
    {
    
    
        iPosEnd = sCopy.find(sSeperator);
        if (iPosEnd == -1 )
        {
    
    
            vToken.push_back(sCopy);
            break;
        }
        vToken.push_back(sCopy.substr(0, iPosEnd));
        sCopy = sCopy.substr(iPosEnd + 1);
    }
}

In the formal parameter list of the function, vToken is the output substring group.
== When the delimiter we specified cannot be found in the find() function, the return value is -1 ==.

Method 2. Use CString's built-in functions

This method is more complicated and needs to include the cstring header file. The function code is as follows:

void stringToken(string sLine, const char* pSeperator, vector<char*>& vToken)
{
    
    
    char* cstr = new char[sLine.length()+1];
    strcpy(cstr, sLine.c_str());
    char*p=strtok(cstr, pSeperator);
    vToken.push_back(p);
    while(p)
    {
    
    
        p=strtok(NULL, pSeperator);
        if(!p)
            break;
        vToken.push_back(p);
    }
}

to sum up

One of the two methods is to use strcpy (character array copy) and strtok (character array segmentation) in c_string, and the other is to use find() and substr() of the C++ string class.
The first method returns a collection of string objects, and the second method returns a collection of character arrays. Both methods can be used directly, please make your choice.

If it works for you, you might as well give a thumbs up~~~~~~~

Guess you like

Origin blog.csdn.net/GeomasterYi/article/details/106863228