用stringstream可以用指定字符分割字符串:

默认分割空格、tab、回车换行

#include <iostream>
#include <sstream>
#include <vector>
 
using namespace std;
 
int main() {
    string str = "hello world sperated by   spaces\tand\nhuiche";
 
    vector<string> arr;
    istringstream ss(str);
    string word;
    while(ss>>word) {
        arr.push_back(word);
    }
 
    for(size_t i=0; i<arr.size(); i++) {
        cout << arr[i] << endl;
    }
     
    return 0;
}

利用指定字符分割字符串

#include <iostream>
#include <sstream>
#include <vector>
 
using namespace std;
 
int main() {
        std::string data = "1_2_3_4_5_6";
        std::stringstream ss(data);
        std::string item;
        queue<string> q;
        cout << data << endl;
        while (std::getline(ss, item, '_')) 
            cout << item << ' ';  
}

//1_2_3_4_5_6
//1 2 3 4 5 6 


posted @ 2018-11-30 14:53  narjaja  阅读(7942)  评论(0编辑  收藏  举报