How to split string using istringstream with other delimiter than whitespace?

前端 未结 3 1176
醉话见心
醉话见心 2020-12-23 09:34

The following trick using istringstream to split a string with white spaces.

int main() {
    string sentence(\"Cpp is fun\");
    istringstream         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-23 10:17

    Generally speaking the istringstream approach is slow/inefficient and requires at least as much memory as the string itself (what happens when you have a very large string?). The C++ String Toolkit Library (StrTk) has the following solution to your problem:

    #include 
    #include 
    #include 
    #include "strtk.hpp"
    int main()
    {
       std::string sentence1( "Cpp is fun" );
       std::vector vec;
       strtk::parse(sentence1," ",vec);
    
       std::string sentence2( "Cpp,is|fun" );
       std::deque deq;
       strtk::parse(sentence2,"|,",deq);
    
       return 0;
    }
    

    More examples can be found Here

提交回复
热议问题