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

后端 未结 20 2117
时光说笑
时光说笑 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-22 00:07

    For string delimiter

    Split string based on a string delimiter. Such as splitting string "adsf-+qwret-+nvfkbdsj-+orthdfjgh-+dfjrleih" based on string delimiter "-+", output will be {"adsf", "qwret", "nvfkbdsj", "orthdfjgh", "dfjrleih"}

    #include 
    #include 
    #include 
    
    using namespace std;
    
    // for string delimiter
    vector split (string s, string delimiter) {
        size_t pos_start = 0, pos_end, delim_len = delimiter.length();
        string token;
        vector res;
    
        while ((pos_end = s.find (delimiter, pos_start)) != string::npos) {
            token = s.substr (pos_start, pos_end - pos_start);
            pos_start = pos_end + delim_len;
            res.push_back (token);
        }
    
        res.push_back (s.substr (pos_start));
        return res;
    }
    
    int main() {
        string str = "adsf-+qwret-+nvfkbdsj-+orthdfjgh-+dfjrleih";
        string delimiter = "-+";
        vector v = split (str, delimiter);
    
        for (auto i : v) cout << i << endl;
    
        return 0;
    }
    


    Output

    adsf
    qwret
    nvfkbdsj
    orthdfjgh
    dfjrleih
    




    For single character delimiter

    Split string based on a character delimiter. Such as splitting string "adsf+qwer+poui+fdgh" with delimiter "+" will output {"adsf", "qwer", "poui", "fdg"h}

    #include 
    #include 
    #include 
    
    using namespace std;
    
    vector split (const string &s, char delim) {
        vector result;
        stringstream ss (s);
        string item;
    
        while (getline (ss, item, delim)) {
            result.push_back (item);
        }
    
        return result;
    }
    
    int main() {
        string str = "adsf+qwer+poui+fdgh";
        vector v = split (str, '+');
    
        for (auto i : v) cout << i << endl;
    
        return 0;
    }
    


    Output

    adsf
    qwer
    poui
    fdgh
    

提交回复
热议问题