C++ split & replace

It’s hard to believe, but after many revisions of the C++ standard, we still don’t have built-in implementations for basic operations like split and replace. See the discussions on Stack Overflow for split and replace.

Here are my basic implementations, they should work for most purposes.

Split

vector<string> split(string const& str, string const& delim) {
    vector<string> tokens;
    size_t start = 0, end;
    do {
        end = str.find(delim, start);
        auto token = str.substr(start, end - start);
        if (!token.empty()) {
            tokens.push_back(token);
        }
        start = end + delim.size();
    } while (end != string::npos);
    return tokens;
}

Replace

string replace(string const& str, string const& old, string const& nu) {
    string res;
    size_t start = 0, end;
    do {
        end = str.find(old, start);
        res += str.substr(start, end - start) + nu;
        start = end + old.size();
    } while (end != string::npos);
    return res;
}

Some tests

void assertEquals(string expected, string actual) {
    if (expected == actual) {
        cout << "PASSED\n";
    } else {
        cout << "FAILED\n";
    }
}


void assertEquals(vector<string> expected, vector<string> actual) {
    if (expected == actual) {
        cout << "PASSED\n";
    } else {
        cout << "FAILED\n";
    }
}

int main() {
    assertEquals({"a", "b", "c"}, split("a,b,c", ","));
    assertEquals({"a", "b", "c"}, split("a->b->c", "->"));
    assertEquals({"a", "b", "c"}, split("a->b->c->", "->"));

    assertEquals("abc", replace("a*b*c", "*", ""));
    assertEquals("abc", replace("a=>b=>c", "=>", ""));
    return 0;
}

These implementations seem short and clear to me, which makes it easier to remember. I hope it helps.


by

Tags: