Skip to main content
added 15 characters in body
Source Link

Loki Astari's ideas will work (for the most part) except for the last one, in one special (but certainly no less important) case: If the string being split is all spaces.

This can be fixed with a simple conditional statement:

std::string trim(std::string const& str)
{
    std::size_t first = str.find_first_not_of(' ');

    // If there is no non-whitespace character, both first and last will be std::string::npos (-1)
    // There is no point in checking both, since if either doesn't work, the
    // other won't work, either.
    if(first == -1std::string::npos)
        return "";

    std::size_t last  = str.find_last_not_of(' ');

    return str.substr(first, last-first+1);
}

Loki Astari's ideas will work (for the most part) except for the last one, in one special (but certainly no less important) case: If the string being split is all spaces.

This can be fixed with a simple conditional statement:

std::string trim(std::string const& str)
{
    std::size_t first = str.find_first_not_of(' ');

    // If there is no non-whitespace character, both first and last will be -1
    // There is no point in checking both, since if either doesn't work, the
    // other won't work, either.
    if(first == -1)
        return "";

    std::size_t last  = str.find_last_not_of(' ');

    return str.substr(first, last-first+1);
}

Loki Astari's ideas will work (for the most part) except for the last one, in one special (but certainly no less important) case: If the string being split is all spaces.

This can be fixed with a simple conditional statement:

std::string trim(std::string const& str)
{
    std::size_t first = str.find_first_not_of(' ');

    // If there is no non-whitespace character, both first and last will be std::string::npos (-1)
    // There is no point in checking both, since if either doesn't work, the
    // other won't work, either.
    if(first == std::string::npos)
        return "";

    std::size_t last  = str.find_last_not_of(' ');

    return str.substr(first, last-first+1);
}
Source Link

Loki Astari's ideas will work (for the most part) except for the last one, in one special (but certainly no less important) case: If the string being split is all spaces.

This can be fixed with a simple conditional statement:

std::string trim(std::string const& str)
{
    std::size_t first = str.find_first_not_of(' ');

    // If there is no non-whitespace character, both first and last will be -1
    // There is no point in checking both, since if either doesn't work, the
    // other won't work, either.
    if(first == -1)
        return "";

    std::size_t last  = str.find_last_not_of(' ');

    return str.substr(first, last-first+1);
}