From fbb55a372fba2d0bc10d829d6829440d51e21e77 Mon Sep 17 00:00:00 2001 From: Martin Mares Date: Sat, 7 Jan 2012 15:25:47 +0100 Subject: [PATCH] String: Added str_starts_with() and str_ends_with() --- ucw/string.c | 24 +++++++++++++++++++++++- ucw/string.h | 8 +++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/ucw/string.c b/ucw/string.c index bd9303ee..d6dc7bd5 100644 --- a/ucw/string.c +++ b/ucw/string.c @@ -2,7 +2,7 @@ * UCW Library -- String Routines * * (c) 2006 Pavel Charvat - * (c) 2007--2008 Martin Mares + * (c) 2007--2012 Martin Mares * * This software may be freely distributed and used according to the terms * of the GNU Lesser General Public License. @@ -13,6 +13,8 @@ #include "ucw/lib.h" #include "ucw/string.h" +#include + #ifdef CONFIG_DARWIN uns strnlen(const char *str, uns n) @@ -49,3 +51,23 @@ str_count_char(const char *str, uns chr) i++; return i; } + +int +str_starts_with(const char *haystack, const char *needle) +{ + while (*needle) + if (*haystack++ != *needle++) + return 0; + return 1; +} + +int +str_ends_with(const char *haystack, const char *needle) +{ + int hlen = strlen(haystack); + int nlen = strlen(needle); + if (hlen < nlen) + return 0; + else + return !memcmp(haystack + hlen - nlen, needle, nlen); +} diff --git a/ucw/string.h b/ucw/string.h index 935da33b..8cfe1645 100644 --- a/ucw/string.h +++ b/ucw/string.h @@ -2,7 +2,7 @@ * UCW Library -- String Routines * * (c) 2006 Pavel Charvat - * (c) 2007--2008 Martin Mares + * (c) 2007--2012 Martin Mares * * This software may be freely distributed and used according to the terms * of the GNU Lesser General Public License. @@ -20,6 +20,12 @@ uns strnlen(const char *str, uns n); char *str_format_flags(char *dest, const char *fmt, uns flags); uns str_count_char(const char *str, uns chr); +/** Returns a non-zero value if @haystack starts with @needle. **/ +int str_starts_with(const char *haystack, const char *needle); + +/** Returns a non-zero value if @haystack ends with @needle. **/ +int str_ends_with(const char *haystack, const char *needle); + /* str-esc.c */ char *str_unesc(char *dest, const char *src); -- 2.39.5