虽然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;
}