From 6c927109ecec502d5554ce22c9fe6c87018755ae Mon Sep 17 00:00:00 2001 From: mrbesen Date: Tue, 29 Sep 2020 15:12:46 +0200 Subject: [PATCH] start/endsWith --- inc/util.h | 4 ++++ src/Util.cpp | 16 ++++++++++++++++ tests/main.cpp | 3 ++- tests/utilstest.cpp | 21 +++++++++++++++++++++ 4 files changed, 43 insertions(+), 1 deletion(-) diff --git a/inc/util.h b/inc/util.h index da2aa52..ec6b5ea 100644 --- a/inc/util.h +++ b/inc/util.h @@ -12,4 +12,8 @@ void toLower(const std::string& in, std::string& out); //copy toLower void toLower(std::string& in); //inplace toLower +bool endsWith(const std::string& str, const std::string& ending); + +bool startsWith(const std::string& str, const std::string& start); + } \ No newline at end of file diff --git a/src/Util.cpp b/src/Util.cpp index d759bf1..e13c9b4 100644 --- a/src/Util.cpp +++ b/src/Util.cpp @@ -54,3 +54,19 @@ void mrbesen::Util::toLower(std::string& in) { in[p] = std::tolower(in[p]); } } + +bool mrbesen::Util::endsWith(const std::string& str, const std::string& ending) { + size_t es = ending.size(); + size_t ss = str.size(); + if(es > ss) return false; + if(es == 0) return true; + + return str.rfind(ending) == (ss - es); +} + +bool mrbesen::Util::startsWith(const std::string& str, const std::string& start) { + if(start.size() > str.size()) return false; + if(start.size() == 0) return true; + + return str.find(start) == 0; +} diff --git a/tests/main.cpp b/tests/main.cpp index 9e0774a..1e2e9f6 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -9,8 +9,9 @@ int testFiles_extention(); int testUtil_Count(); int testUtil_equalsIgnoreCase(); int testUtil_toLower(); +int testUtil_start_endWith(); -test_t tests[] = {testFiles_parent, testFiles_file, testFiles_extention, testUtil_Count, testUtil_equalsIgnoreCase, testUtil_toLower, NULL}; +test_t tests[] = {testFiles_parent, testFiles_file, testFiles_extention, testUtil_Count, testUtil_equalsIgnoreCase, testUtil_toLower, testUtil_start_endWith, NULL}; int main(int argc, char** argv) { diff --git a/tests/utilstest.cpp b/tests/utilstest.cpp index 8712d9e..c0fe73d 100644 --- a/tests/utilstest.cpp +++ b/tests/utilstest.cpp @@ -68,3 +68,24 @@ int testUtil_toLower() { return TESTGOOD; } + + +int testUtil_start_endWith() { + std::string a = "abcdefghijklm"; + + ASSERT(startsWith(a, ""), ""); + ASSERT(startsWith(a, "a"), ""); + ASSERT(!startsWith(a, "b"), ""); + ASSERT(!startsWith(a, "abcdefghijklmn"), ""); + ASSERT(!startsWith(a, "abcdefhhijklm"), ""); + ASSERT(startsWith(a, a), ""); + + ASSERT(endsWith(a, ""), ""); + ASSERT(endsWith(a, "m"), ""); + ASSERT(!endsWith(a, "n"), ""); + ASSERT(!endsWith(a, "abcdefghijklmn"), ""); + ASSERT(!endsWith(a, "abcdefhhijklm"), ""); + ASSERT(endsWith(a, a), ""); + + return TESTGOOD; +} \ No newline at end of file