STL string utils

STL’s std::string doesn’t have methods for transforming the string to upper or lower case or for trimming (as other string implementations, such as CString, have). I’ve noticed that many people don’t know how to implement such functions, so I’ll show you here how to do that.

class stringutils
{
public:
	static void make_upper(std::string& text)
	{
		std::transform(text.begin(), text.end(), text.begin(), toupper);
	}

	static void make_lower(std::string& text)
	{
		std::transform(text.begin(), text.end(), text.begin(), tolower);
	}

	static void trim_left(std::string& text)
	{
		if(!text.empty())
		{
			std::string::iterator pos = text.begin();
			while(pos != text.end() && isspace(*pos)) pos++;

			text.erase(text.begin(), pos);
		}
	}

	static void trim_left(std::string& text, const char* toremove)
	{
		if(!text.empty())
		{
			std::string::size_type pos = text.find_first_not_of(toremove);
			if(std::string::npos != pos) text.erase(0, pos);
			else text.clear();
		}
	}

	static void trim_right(std::string& text)
	{
		if(!text.empty())
		{
			std::string::iterator pos = text.end() - 1;
			while(pos != text.begin() && isspace(*pos)) pos--;

			text.erase(pos+1, text.end());
		}
	}

	static void trim_right(std::string& text, const char* toremove)
	{
		if(!text.empty())
		{
			std::string::size_type pos = text.find_last_not_of(toremove);
			if(std::string::npos != pos) text.erase(pos + 1);
			else text.clear();
		}
	}
};

You can use it like this:

std::string text = " \r\n sample text \r\n ";

stringutils::make_upper(text);
std::cout << text << std::endl;

stringutils::trim_left(text);
std::cout << text << std::endl;

stringutils::trim_right(" \r\n");
std::cout << text << std::endl;

1 thought on “STL string utils”

  1. There is a good reason for which the Standard Library does not have functions to convert strings to uppercase/lowercase.

    It is the same reason for which there is no standard “stricmp”.

    These conversions are locale-sensitive. C++ has left the “one-global-locale” approach inherited from C behind.

    Since one likes Standard facilities so much, I think one might prefer:

    tolower (char_type, const locale &)
    toupper (char_type, const locale &)
    isspace (char_type, const locale &)

    from

    instead of

    tolower (char)
    toupper (char)
    isspace (char)

    from -or-whatever.

    Also, one might want to use the “eq” function of the “character traits” template argument instead of the == operator.

    Otherwise, people who actually _use_ the “character traits” will get inconsistent behaviour.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.