Splitting a string by a character

前端 未结 8 952
夕颜
夕颜 2020-11-27 05:18

I know this is a quite easy problem but I just want to solve it for myself once and for all

I would simply like to split a string into an array using a character as

8条回答
  •  春和景丽
    2020-11-27 05:56

    I inherently dislike stringstream, although I'm not sure why. Today, I wrote this function to allow splitting a std::string by any arbitrary character or string into a vector. I know this question is old, but I wanted to share an alternative way of splitting std::string.

    This code omits the part of the string you split by from the results altogether, although it could be easily modified to include them.

    #include 
    #include 
    
    void split(std::string str, std::string splitBy, std::vector& tokens)
    {
        /* Store the original string in the array, so we can loop the rest
         * of the algorithm. */
        tokens.push_back(str);
    
        // Store the split index in a 'size_t' (unsigned integer) type.
        size_t splitAt;
        // Store the size of what we're splicing out.
        size_t splitLen = splitBy.size();
        // Create a string for temporarily storing the fragment we're processing.
        std::string frag;
        // Loop infinitely - break is internal.
        while(true)
        {
            /* Store the last string in the vector, which is the only logical
             * candidate for processing. */
            frag = tokens.back();
            /* The index where the split is. */
            splitAt = frag.find(splitBy);
            // If we didn't find a new split point...
            if(splitAt == string::npos)
            {
                // Break the loop and (implicitly) return.
                break;
            }
            /* Put everything from the left side of the split where the string
             * being processed used to be. */
            tokens.back() = frag.substr(0, splitAt);
            /* Push everything from the right side of the split to the next empty
             * index in the vector. */
            tokens.push_back(frag.substr(splitAt+splitLen, frag.size()-(splitAt+splitLen)));
        }
    }
    

    To use, just call like so...

    std::string foo = "This is some string I want to split by spaces.";
    std::vector results;
    split(foo, " ", results);
    

    You can now access all the results in the vector at will. Simple as that - no stringstream, no third party libraries, no dropping back to C!

提交回复
热议问题