Skip to content

Instantly share code, notes, and snippets.

@z4none
Last active April 20, 2022 09:52
Show Gist options
  • Save z4none/c9750e76fec08c2c6a4fc8ab1c200d47 to your computer and use it in GitHub Desktop.
Save z4none/c9750e76fec08c2c6a4fc8ab1c200d47 to your computer and use it in GitHub Desktop.
[c++ string startswith / endswith]
//
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;
}
@Luadveand
Copy link

Its works flawlessly. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment