Derek wrote:
A common technique for trimming leading and trailing spaces
from std::string is the following:
string s(" blah blah blah ");
const char* ws= " \t\r";
string::size_type not_white;
// trim leading whitespace
not_white = s.find_first_not_of(ws);
s.erase(0, not_white);
// trim trailing space
not_white = s.find_last_not_of(ws);
s.erase(not_white+1); /*** Is this safe? ***/
// ^^^^^^^^^^^
My question is about the underlined not_white+1. What if
the find_last_not_of call returns string::npos, as would
happen if s was a blank string. It seems to work with
all of my compilers, but it seems dubious to increment
string::npos.
npos is defined as -1 converted to string::size_type, which is an
unsigned integral type. As per the rules of unsigned types, -1 becomes
the largest representable value. Adding 1 causes this value to wrap
around to 0. Therefore, the result will be equivalent to
s.erase(0);
As far as I can tell, there's nothing wrong with this. It should make
's' empty (if it isn't already -- in your example it should already be).
This seems to give the expected result in your code, but it may be a bit
confusing. It may not be immediately obvious to someone reading the code
that it is correctly handling this case, and therefore it might be
worthwhile to make handling of it explicit. But that's your call.
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.