Splitting a string by a character

前端 未结 8 1005
夕颜
夕颜 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:53

    Another way (C++11/boost) for people who like RegEx. Personally I'm a big fan of RegEx for this kind of data. IMO it's far more powerful than simply splitting strings using a delimiter since you can choose to be be a lot smarter about what constitutes "valid" data if you wish.

    #include 
    #include     // copy
    #include      // back_inserter
    #include         // regex, sregex_token_iterator
    #include 
    
    int main()
    {
        std::string str = "08/04/2012";
        std::vector tokens;
        std::regex re("\\d+");
    
        //start/end points of tokens in str
        std::sregex_token_iterator
            begin(str.begin(), str.end(), re),
            end;
    
        std::copy(begin, end, std::back_inserter(tokens));
    }
    

提交回复
热议问题