Commit 3f1ee32c by Maarten L. Hekkelman

better trim

parent cd28ab58
...@@ -190,22 +190,41 @@ std::string trim_left_copy(std::string_view s) ...@@ -190,22 +190,41 @@ std::string trim_left_copy(std::string_view s)
void trim_left(std::string &s) void trim_left(std::string &s)
{ {
auto b = s.begin(); auto in = s.begin(), out = s.begin();
while (b != s.end())
while (in != s.end() and std::isspace(*in))
++in;
if (in == s.end())
s.clear();
else if (in != out)
{ {
if (not std::isspace(*b)) while (in != s.end())
break; *out++ = *in++;
s.erase(out, s.end());
b = std::next(b);
} }
s.erase(s.begin(), b);
} }
void trim(std::string &s) void trim(std::string &s)
{ {
trim_right(s); auto in = s.begin(), out = s.begin(), end = s.end();
trim_left(s);
while (end != s.begin() and std::isspace(*(end - 1)))
--end;
while (in != end and std::isspace(*in))
++in;
if (in == end)
s.clear();
else if (in != out)
{
while (in != end)
*out++ = *in++;
s.erase(out, s.end());
}
else if (end != s.end())
s.erase(end, s.end());
} }
std::string trim_copy(std::string_view s) std::string trim_copy(std::string_view s)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment