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.
[sourcecode language='cpp']
#include
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 );
/*
// Code for Trim Leading Spaces only
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 );
*/
/*
// Code for Trim trailing Spaces only
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<
// To avoid a lengthy post I’m excludnig them
// Please put a comment if you sees some issues
return 0;
}
[/sourcecode]
This is question was asked in the MSDN Forums. You can see my reply there.
