Stripping whitespace characters from 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 strip whitespace (space) characters from the start and end of an std::string in C++, in-place modifying the std::string passed in:

void stripWhitespace(std::string& str)
{
	if (str.empty())
		return;

	// use space and tab chars for whitespace...
	static const char* kWhitespaceChars = " \t";

	size_t firstNonWhitespacePos = str.find_first_not_of(kWhitespaceChars, 0);
	if (firstNonWhitespacePos == std::string::npos)
	{
		// we didn't find a non-whitespace char, so set string to empty
		str = "";
		return;
	}

	size_t lastNonWhitespacePos = str.find_last_not_of(kWhitespaceChars);
	if (lastNonWhitespacePos == std::string::npos ||
		lastNonWhitespacePos < firstNonWhitespacePos)
	{
		// this shouldn't really be possible, but something's gone wrong...
		return;
	}

	// extract the string from the non-whitespace start/end chars
	str = str.substr(firstNonWhitespacePos, lastNonWhitespacePos - firstNonWhitespacePos + 1);
}



Archive
Full Index

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


Tags List