From fed3e3305f6437a0d3ccf231585595838369b907 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sun, 30 May 2021 11:20:00 +0200 Subject: Codechange: add function to determine whether are string starts or ends with a given other string --- src/string.cpp | 27 +++++++++++++++++++++++++++ src/string_func.h | 3 +++ 2 files changed, 30 insertions(+) (limited to 'src') diff --git a/src/string.cpp b/src/string.cpp index e9a619c40..fbb447ee9 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -358,6 +358,33 @@ void StrTrimInPlace(std::string &str) StrRightTrimInPlace(str); } +/** + * Check whether the given string starts with the given prefix. + * @param str The string to look at. + * @param prefix The prefix to look for. + * @return True iff the begin of the string is the same as the prefix. + */ +bool StrStartsWith(const std::string_view str, const std::string_view prefix) +{ + size_t prefix_len = prefix.size(); + if (str.size() < prefix_len) return false; + return str.compare(0, prefix_len, prefix, 0, prefix_len) == 0; +} + +/** + * Check whether the given string ends with the given suffix. + * @param str The string to look at. + * @param suffix The suffix to look for. + * @return True iff the end of the string is the same as the suffix. + */ +bool StrEndsWith(const std::string_view str, const std::string_view suffix) +{ + size_t suffix_len = suffix.size(); + if (str.size() < suffix_len) return false; + return str.compare(str.size() - suffix_len, suffix_len, suffix, 0, suffix_len) == 0; +} + + /** Scans the string for colour codes and strips them */ void str_strip_colours(char *str) { diff --git a/src/string_func.h b/src/string_func.h index 2e258fbd2..0cbf26d6b 100644 --- a/src/string_func.h +++ b/src/string_func.h @@ -51,6 +51,9 @@ bool strtolower(std::string &str, std::string::size_type offs = 0); bool StrValid(const char *str, const char *last) NOACCESS(2); void StrTrimInPlace(std::string &str); +bool StrStartsWith(const std::string_view str, const std::string_view prefix); +bool StrEndsWith(const std::string_view str, const std::string_view suffix); + /** * Check if a string buffer is empty. * -- cgit v1.2.3-54-g00ecf