Add str_endswith() and strcase_endswith()

This commit is contained in:
Andrew Bettison 2017-10-20 09:48:19 +10:30
parent fc478d07ff
commit c64faadb85
2 changed files with 33 additions and 0 deletions

20
str.c
View File

@ -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);

13
str.h
View File

@ -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 <andrew@servalproject.com>
*/
int str_endswith(const char *str, const char *substring, const char **startp);
/* Case-insensitive form of str_endswith().
* @author Andrew Bettison <andrew@servalproject.com>
*/
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[].