string: add lstrip, rstrip, strip

This commit is contained in:
Danny Robson 2022-05-02 14:26:06 +10:00
parent 3ffd895958
commit b7f8d73d95
2 changed files with 49 additions and 0 deletions

View File

@ -101,6 +101,29 @@ namespace cruft {
{
return transform (val, ::tolower);
}
inline std::string_view
lstrip (std::string_view str)
{
auto const pos = std::find_if_not (std::begin (str), std::end (str), ascii::is_space);
return { pos, std::end (str) };
}
inline std::string_view
rstrip (std::string_view str)
{
auto const pos = std::find_if_not (std::rbegin (str), std::rend (str), ascii::is_space);
return { str.begin (), pos.base () };
}
inline std::string_view
strip (std::string_view str)
{
return lstrip (rstrip (str));
}
}

View File

@ -287,6 +287,31 @@ void test_equality_lower (cruft::TAP::logger &tap)
}
///////////////////////////////////////////////////////////////////////////////
static void
test_strip (cruft::TAP::logger &tap)
{
static constexpr struct {
char const *val;
char const *expected_l;
char const *expected_r;
char const *msg;
} TESTS[] = {
{ "asdf", "asdf", "asdf", "no stripping" },
{ "", "", "", "empty string" },
{ " ", "", "", "only space" },
{ " \nasdf", "asdf", " \nasdf", "left space" },
{ "asdf \n", "asdf \n", "asdf", "right space" },
{ " asdf ", "asdf ", " asdf", "both space" },
};
for (auto const &t: TESTS) {
tap.expect_eq (t.expected_l, cruft::lstrip (t.val), "lstrip: {}", t.msg);
tap.expect_eq (t.expected_r, cruft::rstrip (t.val), "rstrip: {}", t.msg);
}
}
///////////////////////////////////////////////////////////////////////////////
int
main (int, char**)
@ -301,6 +326,7 @@ main (int, char**)
test_comparator_less (tap);
test_less_lower (tap);
test_equality_lower (tap);
test_strip (tap);
return tap.status ();
}