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

前端 未结 3 1163
醉话见心
醉话见心 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:02
    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main()
    {
      std::istringstream iss { "Cpp|is|fun" };
    
      std::string s;
      while ( std::getline( iss, s, '|' ) )
        std::cout << s << std::endl;
    
      return 0;
    }
    

    Demo

    0 讨论(0)
  • 2020-12-23 10:15

    The following code uses a regex to find the "|" and split the surrounding elements into an array. It then prints each of those elements, using cout, in a for loop.

    This method allows for splitting with regex as an alternative.

    #include <iostream>
    #include <string>
    #include <regex>
    #include <algorithm>
    #include <iterator>
        
    using namespace std;
    
    
    vector<string> splitter(string in_pattern, string& content){
        vector<string> split_content;
    
        regex pattern(in_pattern);
        copy( sregex_token_iterator(content.begin(), content.end(), pattern, -1),
        sregex_token_iterator(),back_inserter(split_content));  
        return split_content;
    }
        
    int main()
    {   
    
        string sentence = "This|is|the|sentence";
        //vector<string> words = splitter(R"(\s+)", sentence); // seperate by space
        vector<string> words = splitter(R"(\|)", sentence);
    
        for (string word: words){cout << word << endl;}
    
    }   
    
    0 讨论(0)
  • 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 <string>
    #include <vector>
    #include <deque>
    #include "strtk.hpp"
    int main()
    {
       std::string sentence1( "Cpp is fun" );
       std::vector<std::string> vec;
       strtk::parse(sentence1," ",vec);
    
       std::string sentence2( "Cpp,is|fun" );
       std::deque<std::string> deq;
       strtk::parse(sentence2,"|,",deq);
    
       return 0;
    }
    

    More examples can be found Here

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