How to trim a std::string? | Stack Overflow | GitHub | Query Bro

How to trim a std::string?

EDIT Since c++17, some parts of the standard library were removed. Fortunately, starting with c++11, we have lambdas which are a superior Using Boost’s string algorithms would be easiest:

#include <boost/algorithm/string.hpp>

std::string str("hello world! ");

str is now "hello world!". There’s also trim_left and trim, which trims both sides.

Second Solution : –

std::string choppa(const std::string &t, const std::string &ws)
    std::string str = t;
    size_t found;
    found = str.find_last_not_of(ws);
    if (found != std::string::npos)
        str.clear();            // str is all whitespace

    return str;

This works for the null case as well. 🙂

Leave a Comment