Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing integers with STL

Tags:

c++

parsing

stl

Here is a beautiful way to parse ints and store them in a vector, provided they are space delimited (from Split a string in C++?):

#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;

    string s = "3 2 1";
    istringstream iss(s);
    vector<int> tokens;

    copy(istream_iterator<int>(iss),
         istream_iterator<int>(),
         back_inserter<vector<int> >(tokens));
}

Is it possible to specify another delimeter (eg ", ") while keeping something similar?

like image 780
pgrandjean Avatar asked Oct 15 '13 13:10

pgrandjean


1 Answers

You can generalise the string splitting by using a regular expression (C++11). This function tokenises your string by splitting it on a regex.

vector<string> split(const string& input, const regex& regex) {
    sregex_token_iterator
        first(input.begin(), input.end(), regex, -1),
        last;
    return vector<string>(first, last);
}

For your example, to split on ',' pass regex(",") into the function.

#include <iostream>
#include <string>
#include <regex>
#include <vector>

using namespace std;

vector<string> split(const string& input, const regex& regex) {
    sregex_token_iterator
        first(input.begin(), input.end(), regex, -1),
        last;
    return vector<string>(first, last);
}

int main() {

    const regex r = regex(",");
    const string s = "1,2,3";

    vector<string> t = split(s, r);
    for (size_t i = 0; i < t.size(); ++i) {

        cout << "[" << t[i] << "] ";
    }
    cout << endl;

    return 0;
}
like image 89
dwxw Avatar answered Nov 15 '22 22:11

dwxw