A string tokenizer in C++ that allows multiple separators

后端 未结 3 717
陌清茗
陌清茗 2021-02-15 16:45

Is there a way to tokenize a string in C++ with multiple separators? In C# I would have done:

string[] tokens = \"adsl, dkks; dk\".Split(new [] { \",\", \" \", \         


        
3条回答
  •  臣服心动
    2021-02-15 17:03

    Something like that will do:

    void tokenize_string(const std::string &original_string, const std::string &delimiters, std::vector *tokens)
    {
            if (NULL == tokens) return;
    
            size_t pos_start = original_string.find_first_not_of(delimiters);
            size_t pos_end   = original_string.find_first_of(delimiters, pos_start);
    
            while (std::string::npos != pos_start)
            {
                    tokens->push_back(original_string.substr(pos_start, pos_end - pos_start));
                    pos_start = original_string.find_first_not_of(delimiters, pos_end);
                    pos_end   = original_string.find_first_of(delimiters, pos_start);
            }
    }
    

提交回复
热议问题