utility: add string trimming function.

This commit is contained in:
Luca Schlecker 2022-06-06 18:04:05 +02:00 committed by Farook Al-Sammarraie
parent 8d0d4c80ee
commit 982e62eabf
2 changed files with 44 additions and 0 deletions

View File

@ -827,5 +827,37 @@ namespace crow
return res;
}
std::string trim(const std::string& v)
{
if (v.empty())
return "";
size_t begin = 0, end = v.length();
size_t i;
for (i = 0; i < v.length(); i++)
{
if (!std::isspace(v[i]))
{
begin = i;
break;
}
}
if (i == v.length())
return "";
for (i = v.length(); i > 0; i--)
{
if (!std::isspace(v[i - 1]))
{
end = i;
break;
}
}
return v.substr(begin, end - begin);
}
} // namespace utility
} // namespace crow

View File

@ -3112,3 +3112,15 @@ TEST_CASE("task_timer")
io_service.stop();
io_thread.join();
} // task_timer
TEST_CASE("trim")
{
CHECK(utility::trim("") == "");
CHECK(utility::trim("0") == "0");
CHECK(utility::trim(" a") == "a");
CHECK(utility::trim("b ") == "b");
CHECK(utility::trim(" c ") == "c");
CHECK(utility::trim(" a b ") == "a b");
CHECK(utility::trim(" ") == "");
}