C++ String去除头尾空格 实现trim()方法

虽然C++11的标准库中并没有提供trim()方法,但我们可以使用string的find_first_not_of,和find_last_not_of方法实现trim()

#include <iostream>
#include <string>

std::string& trim(std::string &);

int main() 
{
    std::string str = " Hello World ";
    std::cout << str << " size:" << s.size() << std::endl;
    std::cout << trim(s) << " size:" << trim(s).size() << std::endl;

    return 0;
}

std::string& trim(std::string &s) 
{
    if (s.empty()) 
    {
        return s;
    }

    s.erase(0,s.find_first_not_of(" "));
    s.erase(s.find_last_not_of(" ") + 1);
    return s;
}
发布了87 篇原创文章 · 获赞 28 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/MakerCloud/article/details/88932437