Parse (split) a string in C++ using string delimiter (standard C++)

后端 未结 20 2141
时光说笑
时光说笑 2020-11-21 23:44

I am parsing a string in C++ using the following:

using namespace std;

string parsed,input=\"text to be parsed\";
stringstream input_stringstream(input);

i         


        
20条回答
  •  攒了一身酷
    2020-11-21 23:55

    As a bonus, here is a code example of a split function and macro that is easy to use and where you can choose the container type :

    #include 
    #include 
    #include 
    
    #define split(str, delim, type) (split_fn>(str, delim))
     
    template 
    Container split_fn(const std::string& str, char delim = ' ') {
        Container cont{};
        std::size_t current, previous = 0;
        current = str.find(delim);
        while (current != std::string::npos) {
            cont.push_back(str.substr(previous, current - previous));
            previous = current + 1;
            current = str.find(delim, previous);
        }
        cont.push_back(str.substr(previous, current - previous));
        
        return cont;
    }
    
    int main() {
        
        auto test = std::string{"This is a great test"};
        auto res = split(test, ' ', std::vector);
        
        for(auto &i : res) {
            std::cout << i << ", "; // "this", "is", "a", "great", "test"
        }
        
        
        return 0;
    }
    

提交回复
热议问题