From b7f8d73d95b5892a6565dc539028e7113eb42e85 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Mon, 2 May 2022 14:26:06 +1000 Subject: [PATCH] string: add lstrip, rstrip, strip --- string.hpp | 23 +++++++++++++++++++++++ test/string.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/string.hpp b/string.hpp index 64a5f0d1..d6dc8ee6 100644 --- a/string.hpp +++ b/string.hpp @@ -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)); + } } diff --git a/test/string.cpp b/test/string.cpp index e9ff3424..2d7e388f 100644 --- a/test/string.cpp +++ b/test/string.cpp @@ -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 (); } \ No newline at end of file