Click here to Skip to main content
Licence 
First Posted 3 Jul 2005
Views 101,282
Bookmarked 10 times

A trim implementation for std::string

This article discusses two implementations of the trim function, applied to std::strings.
5 votes, 35.7%
1

2
3 votes, 21.4%
3
2 votes, 14.3%
4
4 votes, 28.6%
5
2.78/5 - 14 votes
μ 2.85, σa 2.93 [?]

Introduction

The C++ Standard Template Library (STL, for short) provides the handy std::string class, which provides a lot of common string facilities. However, the well-known trim operation was not implemented. The trim operation consists of removing all unused spaces placed before and after the characters into a string. For example, let's say you have a textbox in a program where the user should type their name. Then, the user types the following:

"  Rodrigo C Dias "

It would be interesting if you could remove the spaces before and after the name if, for example, you are about to include this string in a database. In this article, we will discuss two easy implementations of trim, both applied to the std::string class.

First implementation

In this first implementation, the idea is to extract the substring within the string, so we have just what interests. The code is shown below:

void trim1(string& str)
{
  string::size_type pos1 = str.find_first_not_of(' ');
  string::size_type pos2 = str.find_last_not_of(' ');
  str = str.substr(pos1 == string::npos ? 0 : pos1, 
    pos2 == string::npos ? str.length() - 1 : pos2 - pos1 + 1);
}

Really simple, isn't it?

Second implementation, faster

The second implementation is faster, as you can see yourself if you perform some benchmarks as I did. The idea here is to search the string for the last character before the last space characters. If none is found, then the string is composed only of spaces, so it's completely erased (logical, isn't it?). Else we remove the spaces at the end of the string, based on the found index.

Next step, we search for the first character different from space. Then we remove everything before it. The code of this implementation is shown below:

void trim2(string& str)
{
  string::size_type pos = str.find_last_not_of(' ');
  if(pos != string::npos) {
    str.erase(pos + 1);
    pos = str.find_first_not_of(' ');
    if(pos != string::npos) str.erase(0, pos);
  }
  else str.erase(str.begin(), str.end());
}

This implementation is faster because we have two calls to erase, instead of a string copy (more expensive).

Conclusion

The trim method may be very useful sometimes, and we discussed an implementation of a good one if we are working with the std::string class. Below is the simplest example of how to use it, dealing with the previously given input:

std::string name = "  Rodrigo C Dias ";
trim2(name);

And that's all.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Rodrigo Cesar de Freitas Dias

Software Developer

Brazil Brazil

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 Pinmemberenzorv8:08 1 Sep '10  
GeneralUsing pointer arithmetic PinsussPaterArepo17:01 27 Dec '07  
Questionwhy do you need those 'npos' checks PinmemberSUID0:30 26 Jul '07  
GeneralImplementation trim1() is broken Pinmembergubespam13:15 22 May '07  
GeneralRe: Implementation trim1() is broken PinmemberRodrigo C. Dias7:51 23 May '07  
GeneralLicense to use the code Pinmembersharongnt23:04 25 Dec '06  
GeneralRe: License to use the code PinmemberRodrigo C. Dias1:29 26 Dec '06  
GeneralPerfect PinmemberAaron Planell2:42 20 Sep '06  
GeneralAnother one (very simple) PinmemberRichard Lin7:07 12 Jul '05  
GeneralRe: Another one (very simple) PinmemberRodrigo C. Dias1:30 26 Dec '06  
GeneralRe: Another one (very simple) Pinmemberparaplaner120:11 16 Jul '07  
GeneralSimilar implementation Pinmemberberserker_r22:25 3 Jul '05  
I use this

void trim(string &str, const char *delims = " \t\r", bool left = true, bool right = true);
void trimLeft(string &str, const char *delims = " \t\r");
void trimRight(string &str, const char *delims = " \t\r");
 
void trim(string &str, const char *delims, bool left, bool right)
{
if(left)
trimLeft(str, delims);
if(right)
trimRight(str, delims);
}
 
void trimLeft(string &str, const char *delims)
{
str.erase(0, str.find_first_not_of(delims));
}
 
void trimRight(string &str, const char *delims)
{
str.erase(str.find_last_not_of(delims) + 1);
}

GeneralRe: Similar implementation PinmemberCP Visitor0:27 5 Jul '05  
GeneralRe: Similar implementation PinmemberNathan Lewis17:11 6 Apr '06  
GeneralRe: Similar implementation PinmemberSnakefoot14:27 20 Oct '09  
GeneralBoost string algorithms library PinmemberNemanja Trifunovic15:16 3 Jul '05  
GeneralRe: Boost string algorithms library PinmemberRodrigo C. Dias17:39 3 Jul '05  
GeneralRe: Boost string algorithms library PinsussAnonymous2:07 4 Jul '05  
GeneralRe: Boost string algorithms library PinmemberNemanja Trifunovic2:47 4 Jul '05  
GeneralRe: Boost string algorithms library Pinmembersetori880:32 30 Nov '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 3 Jul 2005
Article Copyright 2005 by Rodrigo Cesar de Freitas Dias
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid