From 14b859616ec581c09a9e53895fcba4bc3a21bad3 Mon Sep 17 00:00:00 2001 From: Andrew Bettison Date: Wed, 27 Feb 2013 15:58:32 +1030 Subject: [PATCH] Add strnchr() to str.c --- str.c | 11 +++++++++++ str.h | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/str.c b/str.c index f8b9e47b..28202638 100644 --- a/str.c +++ b/str.c @@ -88,6 +88,17 @@ char *str_toupper_inplace(char *str) return str; } +int strnchr(const char *s, size_t n, char c) +{ + for (; n; --n, ++s) { + if (*s == c) + return s; + if (!*s) + break; + } + return NULL; +} + int str_startswith(const char *str, const char *substring, const char **afterp) { while (*substring && *substring == *str) diff --git a/str.h b/str.h index 58c219fc..c94fef1b 100644 --- a/str.h +++ b/str.h @@ -86,6 +86,13 @@ size_t str_fromprint(unsigned char *dst, const char *src); #define alloca_toprint(dstlen,buf,len) toprint((char *)alloca((dstlen) == -1 ? toprint_len((const char *)(buf),(len), "``") + 1 : (dstlen)), (dstlen), (const char *)(buf), (len), "``") #define alloca_str_toprint(str) toprint_str((char *)alloca(toprint_str_len(str, "``") + 1), -1, (str), "``") +/* Like strchr(3), but only looks for 'c' in the first 'n' characters of 's', stopping at the first + * nul char in 's'. + * + * @author Andrew Bettison + */ +int strnchr(const char *s, size_t n, char c); + /* 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.