Skip to main content
1 of 2

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);
}