From 2077265b2d47e303997c65c4925d68351b046d13 Mon Sep 17 00:00:00 2001 From: Andrew Bettison Date: Thu, 4 Apr 2013 17:42:33 +1030 Subject: [PATCH] Add str_index(), str_rindex(), et al --- str.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/str.h b/str.h index 9c8f15e0..8f2cb724 100644 --- a/str.h +++ b/str.h @@ -93,6 +93,35 @@ size_t str_fromprint(unsigned char *dst, const char *src); */ const char *strnchr(const char *s, size_t n, char c); +/* Like strchr(3) and strrchr(3), but returns the index into the string instead of a pointer, or -1 + * if the character is not found. The '_dfl' variants take a third argument that gives the default + * value to return if the character is not found. + * + * @author Andrew Bettison + */ + +__STR_INLINE ssize_t str_index_dfl(const char *s, char c, ssize_t dfl) +{ + const char *r = strchr(s, c); + return r ? r - s : dfl; +} + +__STR_INLINE ssize_t str_rindex_dfl(const char *s, char c, ssize_t dfl) +{ + const char *r = strrchr(s, c); + return r ? r - s : dfl; +} + +__STR_INLINE ssize_t str_index(const char *s, char c) +{ + return str_index_dfl(s, c, -1); +} + +__STR_INLINE ssize_t str_rindex(const char *s, char c) +{ + return str_rindex_dfl(s, c, -1); +} + /* Check if a given nul-terminated string 'str' starts with a given nul-terminated sub-string. If * so, return 1 and, if afterp is not NULL, set *afterp to point to the character in 'str' * immediately following the substring. Otherwise return 0.