May 4, 2018 at 1:59am UTC
How can we spit strings into arrays / vectors in c++ without any external libraries, such as boosts?
string temp = “Well//Hello//There//Everyone”;
string splittedString[] = temp.split(“//”); // Any method similar to this?
cout << splittedString[0] << endl; // “Well”
cout << splittedString[1] << endl; // “Hello”
cout << splittedString[2] << endl; // “There”
cout << splittedString[3] << endl; // “Everyone”
May 4, 2018 at 2:32am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(const string& s, char delim) {
vector<string> v;
for (size_t start = 0, end; start < s.size(); start = end + 1) {
if ((end = s.find(delim, start)) == s.npos)
end = s.size();
v.push_back(s.substr(start, end - start));
}
return v;
}
int main() {
string s{"one/two/three/four/five/six/seven" };
vector<string> v = split(s, '/' );
for (const auto & x: v) cout << x << '\n' ;
}
Last edited on May 4, 2018 at 3:17am UTC
May 4, 2018 at 2:59am UTC
Yes, I totally get that, but the delimiter can only be one character. The whole process you showed can be done with std::getline(arg1, arg2, arg3). But what if I want the delimiter to be a string? Any method for that?