7

Function to divide strings using string :: find and string :: substr returns fal...

 3 years ago
source link: https://www.codesd.com/item/function-to-divide-strings-using-string-find-and-string-substr-returns-false-tokens.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Function to divide strings using string :: find and string :: substr returns false tokens

advertisements
//splits a string into a vector of multiple tokens
std::vector<string> split_str(std::string& str, const char* delimiter){
    std::vector<string> ret;
    size_t currPos = 0;
    //Add the first element to the vector
    if (str.find(delimiter) != string::npos)
        ret.push_back(str.substr(currPos, str.find(delimiter)));

    while (currPos != str.size() - 1){

        if (str.find(delimiter, currPos) != string::npos){
            //Current at one past the delimiter
            currPos = str.find(delimiter, currPos) + 1;
            //Substring everything from one past the delimiter until the next delimiter
            ret.push_back(str.substr(currPos, str.find(delimiter, currPos)));
        }
        //If last whitespace is not right at the end
        else if (currPos < str.size()){
            //Add the last element to the vector and end the loop
            ret.push_back(str.substr(currPos, str.size()));
            currPos = str.size() - 1;
        }

    }
    return ret;
}

The program is supposed to take a string and a delimiter as an input and return a vector of strings (tokens) as an output. However, when I try it with a simple input such as:

ab bc cd de (delimiter is " ")

The output will be 5 elements: "ab", "bc cd", "cd de", "de", "de"


The problem is that second parameter to std::string::substr() is count not position. Your code should be modified from:

if (str.find(delimiter) != string::npos)
    ret.push_back(str.substr(currPos, str.find(delimiter)));

to this:

auto fpos = str.find(delimiter);
if (fpos != string::npos)
    ret.push_back(str.substr(currPos, fpos - currPos));
    //                                ^^^^^^^^^^^^^^

and so on.

Tags string

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK