diff --git a/include/bx/inline/string.inl b/include/bx/inline/string.inl index e049b0c..4bec9dd 100644 --- a/include/bx/inline/string.inl +++ b/include/bx/inline/string.inl @@ -308,4 +308,24 @@ namespace bx ; } + inline StringView strTrimPrefix(const StringView& _str, const StringView& _prefix) + { + if (hasPrefix(_str, _prefix) ) + { + return StringView(_str.getPtr() + _prefix.getLength(), _str.getTerm() ); + } + + return _str; + } + + inline StringView strTrimSuffix(const StringView& _str, const StringView& _suffix) + { + if (hasSuffix(_str, _suffix) ) + { + return StringView(_str.getPtr(), _str.getTerm() - _suffix.getLength() ); + } + + return _str; + } + } // namespace bx diff --git a/include/bx/string.h b/include/bx/string.h index edb257a..87910b6 100644 --- a/include/bx/string.h +++ b/include/bx/string.h @@ -266,6 +266,12 @@ namespace bx /// Returns string view with whitespace characters trimmed from left and right. StringView strTrimSpace(const StringView& _str); + /// Returns string view with prefix trimmed. + StringView strTrimPrefix(const StringView& _str, const StringView& _prefix); + + /// Returns string view with suffix trimmed. + StringView strTrimSuffix(const StringView& _str, const StringView& _suffix); + /// Find new line. Returns pointer after new line terminator. StringView strFindNl(const StringView& _str); diff --git a/tests/string_test.cpp b/tests/string_test.cpp index 48ee8d8..ca820c4 100644 --- a/tests/string_test.cpp +++ b/tests/string_test.cpp @@ -536,16 +536,22 @@ TEST_CASE("strFindBlock", "") REQUIRE(19 == result.getLength() ); } -TEST_CASE("hasPrefix", "") +TEST_CASE("prefix", "") { REQUIRE( bx::hasPrefix("abvgd-1389.0", "abv") ); REQUIRE(!bx::hasPrefix("abvgd-1389.0", "bvg") ); REQUIRE( bx::hasPrefix("abvgd-1389.0", "") ); + + REQUIRE(0 == bx::strCmp(bx::strTrimPrefix("abvgd-1389.0", "abv"), "gd-1389.0") ); + REQUIRE(0 == bx::strCmp(bx::strTrimPrefix("abvgd-1389.0", "xyz"), "abvgd-1389.0") ); } -TEST_CASE("hasSuffix", "") +TEST_CASE("suffix", "") { REQUIRE( bx::hasSuffix("abvgd-1389.0", "389.0") ); REQUIRE(!bx::hasSuffix("abvgd-1389.0", "1389") ); REQUIRE( bx::hasSuffix("abvgd-1389.0", "") ); + + REQUIRE(0 == bx::strCmp(bx::strTrimSuffix("abvgd-1389.0", "389.0"), "abvgd-1") ); + REQUIRE(0 == bx::strCmp(bx::strTrimSuffix("abvgd-1389.0", "xyz"), "abvgd-1389.0") ); }