Last active
April 20, 2022 09:52
-
-
Save z4none/c9750e76fec08c2c6a4fc8ab1c200d47 to your computer and use it in GitHub Desktop.
[c++ string startswith / endswith]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
bool starts_with(const std::string & str, const std::string & sub, bool ignore_case=false) | |
{ | |
int str_len = str.size(); | |
int sub_len = sub.size(); | |
if (str_len < sub_len) return false; | |
if (ignore_case) | |
{ | |
return std::equal(sub.begin(), sub.end(), | |
str.begin(), [](char a, char b) {return std::tolower(a) == std::tolower(b); }); | |
} | |
return str.compare(0, sub_len, sub) == 0; | |
} | |
// | |
bool ends_with(const std::string& str, const std::string& sub, bool ignore_case = false) | |
{ | |
int str_len = str.size(); | |
int sub_len = sub.size(); | |
if (str_len < sub_len) return false; | |
if (ignore_case) | |
{ | |
return std::equal(sub.begin(), sub.end(), | |
str.begin() + str_len - sub_len, [](char a, char b) {return std::tolower(a) == std::tolower(b); }); | |
} | |
return str.compare(str_len - sub_len, sub_len, sub) == 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Its works flawlessly. Thanks!