Splitting an std::string in C++

Category: cpp, year: 2018

C++ unfortunately does not have very many built-in convenient string-handling methods, although there are libraries like boost and pystring that can be used to obtain functionality that is found in other more modern programming languages.

However, sometimes using external dependencies is not possible or wanted for a variety of reasons.

The following code function snippet is an example of how to split an std::string into an std::vector of strings based on a separator string in C++:

void splitString(const std::string& str, std::vector<std::string>& stringTokens, const std::string& sep)
{
	size_t lastPos = str.find_first_not_of(sep, 0);
	size_t pos = str.find_first_of(sep, lastPos);

	while (lastPos != std::string::npos || pos != std::string::npos)
	{
		stringTokens.push_back(str.substr(lastPos, pos - lastPos));
		lastPos = str.find_first_not_of(sep, pos);
		pos = str.find_first_of(sep, lastPos);
	}
}



Archive
Full Index

linux (4)
cpp (3)
rust (2)
macos (1)
matplotlib (1)
unix (1)


Tags List