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…
- Using custom function for std::string
- Using CString
- 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.
. Here is a simple function which removes white space before and after a string. We’ll call it Trim!
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
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.
#include <windows .h>
#include <iostream .h>
#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


I think this implements Loren’s idea:
http://mlawire.blogspot.com/2009/07/c-whitespace-trimming-functions.html
Agreed! You can customize based on your needs, posted to let people know of such techniques. Thanks!
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 “ \t\r”, but the real solution would involve using isspace().
How do you do this in C?