std::string trim_left(std::string s)
{
s.erase(s.cbegin(), std::find_if(s.cbegin(), s.cend(), [](char c) -> bool { return c != ' '; }));
return s;
}
std::string trim_right(std::string s)
{
s.erase(std::find_if(s.crbegin(), s.crend(), [](char c) -> bool { return c != ' '; }).base(), s.cend());
return s;
}
std::string trim(std::string s)
{
return trim_left(trim_right(std::move(s)));
}
int main(int argc, char **argv)
{
string s = " hello world! ";
cout << "trim_left: " << trim_left(s) << "success" << endl;
cout << "trim_right: " << trim_right(s) << endl;
cout << "trim: " << trim(s) << "success" << endl;
return 0;
}
输出:
trim_left: hello world! success
trim_right: hello world!
trim: hello world!success