C++ Tokenize String

前端 未结 3 1331
小鲜肉
小鲜肉 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:19

    You can use the strtok_r function, but read the man pages carefully so you understand how it maintains state.

    0 讨论(0)
  • 2020-12-11 02:22

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

    std::vector<std::string> inline StringSplit(const std::string &source, const char *delimiter = " ", bool keepEmpty = false)
    {
        std::vector<std::string> 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;
    }
    
    0 讨论(0)
  • 2020-12-11 02:29

    Look at this tutorial, which is by far the best tutorial on tokenization that I have found so far. It covers the best practices in the implementation of different methods that include using getline() and find_first_of() in C++ std, and strtok() in C.

    0 讨论(0)
提交回复
热议问题