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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With