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 2012, Windows 7
Language: C/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;
}

Submitted: February 10, 2014

Return to the snippets listing