Splitting Strings into String arrays

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”
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
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?
Yes, it could be written with getline like this:
1
2
3
4
5
6
7
8
vector<string> split(const string& s, char delim) {
    vector<string> v;
    istringstream sin(s);  // include <sstream>
    string line;
    while (getline(sin, line, delim))
        v.push_back(line);
    return v;
}


The other method is easy to extend to use a string as a delimiter:
1
2
3
4
5
6
7
8
9
vector<string> split(const string& s, string delim) {
    vector<string> v;
    for (size_t start = 0, end; start < s.size(); start = end + delim.size()) {
        if ((end = s.find(delim, start)) == s.npos)
            end = s.size();
        v.push_back(s.substr(start, end - start));
    }
    return v;
}

Topic archived. No new replies allowed.