C++ Tokenize String

前端 未结 3 1378
小鲜肉
小鲜肉 2020-12-11 01:59

I\'m looking for a simple way to tokenize string input without using non default libraries such as Boost, etc.

For example, if the user enters forty_five, I would li

3条回答
  •  长情又很酷
    2020-12-11 02:22

    To convert a string to a vector of tokens (thread safe):

    std::vector inline StringSplit(const std::string &source, const char *delimiter = " ", bool keepEmpty = false)
    {
        std::vector results;
    
        size_t prev = 0;
        size_t next = 0;
    
        while ((next = source.find_first_of(delimiter, prev)) != std::string::npos)
        {
            if (keepEmpty || (next - prev != 0))
            {
                results.push_back(source.substr(prev, next - prev));
            }
            prev = next + 1;
        }
    
        if (prev < source.size())
        {
            results.push_back(source.substr(prev));
        }
    
        return results;
    }
    

提交回复
热议问题