Trimming C++ strings

Posted in Uncategorized by tux4life on July 26, 2009

The c++ string class is one of the most complete implementation of the string library and has functions for every possible string operation one can think of.  But one of the most dearly missed function is the trim() function (to remove the leading and trailing spaces/tabs).

Fortunately, it is very easy to implement an efficient version  the trim function using other member functions of the string class.  This is illustrated in the code snippet shown below.

void trim(std::string& str)
{
std::string trim_chars = ” \t”;
std::string::size_type pos = str.find_last_not_of(trim_chars);
if(pos != std::string::npos) {
str.erase(pos + 1);
pos = str.find_first_not_of(trim_chars);
if(pos != std::string::npos) str.erase(0, pos);
}
else
str.erase(str.begin(), str.end());
}

The logic is pretty simple.  Find the first/last character that is not a space/tab, then remove everything that precedes/follows it.  The else clause handles the case where the string only has spaces or tabs and erases everything.

As a small optimisation, the “trim_chars” variable can be made static so that it is not created and deleted every time the function is called.  This would be particularly helpful if the function called multiple times.

void trim(std::string& str)

{

std::string trim_chars = ” \t”;

std::string::size_type pos = str.find_last_not_of(trim_chars);

if(pos != std::string::npos) {

str.erase(pos + 1);

pos = str.find_first_not_of(trim_chars);

if(pos != std::string::npos) str.erase(0, pos);

}

else

str.erase(str.begin(), str.end());

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: