Split A String With Another String

Description: Small function for splitting a string (using another string) and returning a vector of substrings. Provides option to ignore empty tokens (by default) or not. Needs to include <string>, <vector> and using standard namespace.
Tested Platform: Visual Studio 64-bit, Windows 10
Language: C++
// Splits a string based on another string and returns vector of substrings.
// vector<string> substrings = split("123.23.111.89",".") returns 
// "123", "23", "111" and "89"

vector<string> split(string str, string delim, bool ignoreEmptyTokens = true) {
    vector<string> strings;
    size_t pos = 0;
    string token;

    while ((pos = str.find(delim)) != string::npos) {
        token = str.substr(0, pos);
        if (token == "") {
            if (!ignoreEmptyTokens) {
                strings.push_back(token);
            }
        } 
        else {
            strings.push_back(token);
        }
        str.erase(0, pos + delim.length());
    }

    if (strlen(str.c_str()) > 0) {
        strings.push_back(str);
    }

    return strings;
}

Posted: March 20, 2023

Return to the snippets listing