How to Trim Leading or Trailing Spaces of a String in C++?
C++ provides various string routines for different string operations. but as far I know there’s no function in C++/C for removing the leading or traling spaces. How we could do this? See the tweak code below.
You can make use of find_first_not_of STL function for trimming leading spaces and find_last_not_of function for trimming traling spaces. These functions will not trim the spaces however, it will return the position of charcter first charcter which is not matching with the one we specified and substr function of string class can use to get the sub string from the given string.
The sample code below shows, how to remove the leading and trailing characters.
#include <string>
using namespace std;
void TrimSpaces( string& str)
{
// Trim Both leading and trailing spaces
size_t startpos = str.find_first_not_of(” \t”); // Find the first character position after excluding leading blank spaces
size_t endpos = str.find_last_not_of(” \t”); // Find the first character position from reverse af
// if all spaces or empty return an empty string
if(( string::npos == startpos ) || ( string::npos == endpos))
{
str = “”;
}
else
str = str.substr( startpos, endpos-startpos+1 );
/*
// Trim Leading Spaces
size_t startpos = str.find_first_not_of(” \t”); // Find the first character position after excluding leading blank spaces
if( string::npos != startpos )
str = str.substr( startpos );
*/
/*
// Trim trailing Spaces
size_t endpos = str.find_last_not_of(” \t”); // Find the first character position from reverse af
if( string::npos != endpos )
str = str.substr( 0, endpos+1 );
*/
}
int main( int argc, char* argv[] )
{
string str = “ Leading n Trailing “;
TrimSpaces(str);
cout << str<<endl;
// You can have different type of strings to test the code.
// To avoid a lengthy post I’m excludnig them
// Please put a comment if you sees some issues
return 0;
}
This is question was asked in the MSDN Forums. You can see my reply there.

March 3, 2007 at 12:41 am
You need to check that start != npos. This occurs when the input string consists entirely of spaces. If you don’t check, and you send in all spaces, you get undefined behavior out of the substr() call. When start == npos, you can simply str.resize(0)
March 3, 2007 at 4:33 am
Jeff,
Thanks a lot for pointing out the mistake. At that time i never thought about error checking. but now a days this is one of most visited post in my blog. See the update code. I think operator = is faster tha resize() function since it is doing some relocation but at the time of assignment, it’s managing the new string within allocated memory in this case. Anyway please reply back me if I said something wrong.
Once again thanks alot for pointing out the errors.
March 4, 2007 at 6:15 am
Looks much better.
BTW, you don’t really need to test endpos, because if the string is empty (zero length), find_first_not_of() will return npos. And if the string is entirely spaces, it will also return npos. In both cases, testing startpos is sufficient. In fact, if startpos is npos, then you don’t even need to compute endpos with find_last_not_of(). On the other hand, in both cases where startpos is npos, empty string and all spaces, find_last_not_of() will be very very fast. So it would be only a very minor savings to avoid the find_last_not_of().
Performance of operator=() vs resize() depends on your implementation of std::string. If you can see the internals of your std::string implementation, then you can use whichever is faster. My guess is that most implementation of std::string will be very close performance-wise between the two. I’m using the impl that comes with the Solaris compilers, but I haven’t checked to see what’s fastest for that one.
FYI, regarding your popularity, I found you via a Google search on: “C++” string trim spaces. This was the 7th hit. It’s funny how Google can bump up your site traffic. I had a similar experience with the photography portion of my own website, netjeff.com. For the first 4 months of 2006, for some reason my site was the #1 result on images.google.com for the search term “clouds”. That increased my page hits by more than 500%. But now I’m not even on the first page of hits, and my traffic is back to my usual.
May 18, 2007 at 11:56 am
How to Trim leading and Trailing zero & slash of a String in C++
May 18, 2007 at 11:25 pm
You can pass any string to find_first_not_of or find_last_not_of function. Here I’ve used a space and tabe ( ” \t”) . It’s you application’s logic to choose between the strings. If you want to replace back slash string should be “\\” and if forward slash, it should be “/” and whatever you like to search.
August 8, 2007 at 10:10 pm
Totally Free Condoms
FREE CONDOMS HERE!, Totally Free Condoms, discreetly packaged and shipped.