string::npos + 1 ???

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Derek

    string::npos + 1 ???

    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_ty pe not_white;

    // trim leading whitespace
    not_white = s.find_first_no t_of(ws);
    s.erase(0, not_white);

    // trim trailing space
    not_white = s.find_last_not _of(ws);
    s.erase(not_whi te+1); /*** Is this safe? ***/
    // ^^^^^^^^^^^

    My question is about the underlined not_white+1. What if
    the find_last_not_o f 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.
  • Kevin Goodsell

    #2
    Re: string::npos + 1 ???

    Derek wrote:
    [color=blue]
    > 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_ty pe not_white;
    >
    > // trim leading whitespace
    > not_white = s.find_first_no t_of(ws);
    > s.erase(0, not_white);
    >
    > // trim trailing space
    > not_white = s.find_last_not _of(ws);
    > s.erase(not_whi te+1); /*** Is this safe? ***/
    > // ^^^^^^^^^^^
    >
    > My question is about the underlined not_white+1. What if
    > the find_last_not_o f 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.[/color]

    npos is defined as -1 converted to string::size_ty pe, 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.

    Comment

    Working...