Skip to content

Latest commit

 

History

History
29 lines (23 loc) · 665 Bytes

072 - 去除 string 头尾空格的最好办法.md

File metadata and controls

29 lines (23 loc) · 665 Bytes

https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring

问题

去除 std::string 头尾空格有没有什么好办法?

回答

// trim from start (in place)
static inline void ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
        return !std::isspace(ch);
    }));
}

// trim from end (in place)
static inline void rtrim(std::string &s) {
    s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
        return !std::isspace(ch);
    }).base(), s.end());
}

// trim from both ends (in place)
static inline void trim(std::string &s) {
    ltrim(s);
    rtrim(s);
}