How to trim white space before and after a string?

I will describe in this post three ways to trim a string of given characters…

  1. Using custom function for std::string
  2. Using CString
  3. Using StrTrim shell API function.

Using custom function for std::string

Its bit strange that std::string doesn’t provide a Trim function πŸ˜• , but hey since we’ve got head upon our shoulders we’re gonna write one. :P. Here is a simple function which removes white space before and after a string. We’ll call it Trim! πŸ˜›

[sourcecode language=’cpp’]void Trim( const std::string& StrToTrim, std::string& TrimmedString )
// Find first non whitespace char in StrToTrim
std::string::size_type First = StrToTrim.find_first_not_of( ‘ ‘ );
// Check whether something went wrong?
if( First == std::string::npos )
First = 0;

// Find last non whitespace char from StrToTrim
std::string::size_type Last = StrToTrim.find_last_not_of( ‘ ‘ );
// If something didn’t go wrong, Last will be recomputed to get real length of substring
if( Last != std::string::npos )
Last = ( Last + 1 ) – First;

// Copy such a string to TrimmedString
TrimmedString = StrToTrim.substr( First, Last );

int main()
std::string StrToTrim = ” 32 Nibu babu thomas 2342 2 23 3 “;
std::string TrimmedString = “On return will hold trimmed string”;
Trim( StrToTrim, TrimmedString );

return 0;
//Output is: 32 Nibu babu thomas 2342 2 23 3[/sourcecode]

Using CString

Also CString has a Trim function, if you have the liberty to use CString then that’s another option.

Using StrTrim shell API function

Another option is to use StrTrim shell API function. Here is a demo from MSDN.

[sourcecode language=’cpp’]#include
#include “Shlwapi.h”

void main(void)
//String one
TCHAR buffer[ ] = TEXT(“_!ABCDEFG#”);
TCHAR trim[ ] = TEXT(“#A!_”);

cout << "The string before calling StrTrim: "; cout << buffer; cout << "n"; StrTrim(buffer, trim); cout << "The string after calling StrTrim: "; cout << buffer; cout << "n"; } OUTPUT: - - - - - - The string before calling StrTrim: _!ABCDEFG# The string after calling StrTrim: BCDEFG[/sourcecode]

4 thoughts on “How to trim white space before and after a string?

  1. This is misleading in that you say it trims whitespace, but it only trims β€˜ β€˜, but not ‘t’, ‘r’, etc… Luckily, find_first_not_of and find_last_not_of can take multiple tokens so you can pass β€œ tr”, but the real solution would involve using isspace().

Appreciate your comments...