diff --git a/string.hpp b/string.hpp index 9fe79687a1eab5374f64b9f23f644786c421408e..c8789c15581768e4d7e947a7214b8dd3427efff6 100644 --- a/string.hpp +++ b/string.hpp @@ -374,6 +374,26 @@ namespace rlib { return *this; } + bool starts_with(const std::string &what) const { + if(size() < what.size()) return false; + + std::string::value_type diffBits = 0; + for(auto i = 0; i < what.size(); ++i) { + diffBits = diffBits | (what[i] ^ (*this)[i]); + } + return diffBits == 0; + } + bool ends_with(const std::string &what) const { + if(size() < what.size()) return false; + + std::string::value_type diffBits = 0; + auto offset = size() - what.size(); + for(auto i = 0; i < what.size(); ++i) { + diffBits = diffBits | (what[i] ^ (*this)[offset+i]); + } + return diffBits == 0; + } + template <typename... Args> string &format(Args... args) { return operator=(std::move(impl::format_string(*this, args ...))); diff --git a/test/src/string.cc b/test/src/string.cc index 82d784689d8b8bfc7ea17054582954603768494a..681d44642fd8563837c088c62e82b162bb7b22f6 100644 --- a/test/src/string.cc +++ b/test/src/string.cc @@ -49,6 +49,18 @@ TEST_CASE("rlib::string others", "[string_op]") { test_str = "hello world \n abc def some random "; auto test_str2 = test_str; REQUIRE(" "_rs.join(test_str.split(' ')) == test_str2); + + const rlib::string test_str3 = "|123||"; + REQUIRE(test_str3.starts_with("") == true); + REQUIRE(test_str3.starts_with("|") == true); + REQUIRE(test_str3.starts_with("|123||") == true); + REQUIRE(test_str3.starts_with("1123||") == false); + REQUIRE(test_str3.starts_with("|123|||") == false); + REQUIRE(test_str3.ends_with("") == true); + REQUIRE(test_str3.ends_with("|") == true); + REQUIRE(test_str3.ends_with("23||") == true); + REQUIRE(test_str3.ends_with("1123||") == false); + REQUIRE(test_str3.ends_with("123|||") == false); }