C++Guns – RoboBlog

13.11.2015

std::string trimmed std::string_view

Filed under: Allgemein — Tags: — Thomas @ 13:11

There is no trim() trimmed() member function in std::string. A free function is better.

Here is one nice solution which has a linear running time and not quadratic like using erase(). (Stupid programmer out there)
From:
http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring

std::string trimmed(const std::string &s) {
   auto wsfront=std::find_if_not(s.begin(),s.end(), [](int c){return std::isspace(c);});
   auto wsback=std::find_if_not(s.rbegin(),s.rend(),[](int c){return std::isspace(c);}).base();
   return (wsback<=wsfront ? std::string() : std::string(wsfront,wsback));
}
std::string_view trimmed(std::string_view s) {
    auto wsfront = std::find_if_not(s.begin(),s.end(), [](int c){return std::isspace(c);});
    // base() returns the forward iterator from reverse iterator returned by rbegin()
    auto wsback = std::find_if_not(s.rbegin(),s.rend(),[](int c){return std::isspace(c);}).base();
    return wsback <= wsfront ? std::string_view() : std::string_view(wsfront, wsback-wsfront); //  its a lower than there. F wordpress
}

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress