From c64faadb851a8ea4559378679e5f47701779fce9 Mon Sep 17 00:00:00 2001 From: Andrew Bettison Date: Fri, 20 Oct 2017 09:48:19 +1030 Subject: [PATCH] Add str_endswith() and strcase_endswith() --- str.c | 20 ++++++++++++++++++++ str.h | 13 +++++++++++++ 2 files changed, 33 insertions(+) diff --git a/str.c b/str.c index c081bc52..8eade80b 100644 --- a/str.c +++ b/str.c @@ -417,6 +417,26 @@ int strncase_startswith(const char *str, size_t len, const char *substring, cons return 1; } +int str_endswith(const char *str, const char *substring, const char **startp) { + size_t len = strlen(str); + size_t sublen = strlen(substring); + if (len < sublen || strcmp(&str[len - sublen], substring) != 0) + return 0; + if (startp) + *startp = &str[len - sublen]; + return 1; +} + +int strcase_endswith(const char *str, const char *substring, const char **startp) { + size_t len = strlen(str); + size_t sublen = strlen(substring); + if (len < sublen || strcasecmp(&str[len - sublen], substring) != 0) + return 0; + if (startp) + *startp = &str[len - sublen]; + return 1; +} + int strn_str_cmp(const char *str1, size_t len1, const char *str2) { int r = strncmp(str1, str2, len1); diff --git a/str.h b/str.h index 6fd0e718..c0efeedf 100644 --- a/str.h +++ b/str.h @@ -328,6 +328,19 @@ int strcase_startswith(const char *str, const char *substring, const char **afte */ int strncase_startswith(const char *str, size_t len, const char *substring, const char **afterp); +/* Check if a given nul-terminated string 'str' ends with a given nul-terminated sub-string. If + * so, return 1 and, if startp is not NULL, set *startp to point to the first character of the + * found substring. Otherwise return 0. + * + * @author Andrew Bettison + */ +int str_endswith(const char *str, const char *substring, const char **startp); + +/* Case-insensitive form of str_endswith(). + * @author Andrew Bettison + */ +int strcase_endswith(const char *str, const char *substring, const char **startp); + /* Compare the given string 'str1' of a given length 'len1' with a given nul-terminated string * 'str2'. Equivalent to { str1[len1] = '\0'; return strcmp(str1, str2); } except without modifying * str1[].