]> mj.ucw.cz Git - libucw.git/commitdiff
String: Added str_starts_with() and str_ends_with()
authorMartin Mares <mj@ucw.cz>
Sat, 7 Jan 2012 14:25:47 +0000 (15:25 +0100)
committerMartin Mares <mj@ucw.cz>
Sat, 7 Jan 2012 14:25:47 +0000 (15:25 +0100)
ucw/string.c
ucw/string.h

index bd9303ee8142a92b548e18580830705d3a1e3eab..d6dc7bd5188524f0698e9820217b100da19a7b1e 100644 (file)
@@ -2,7 +2,7 @@
  *     UCW Library -- String Routines
  *
  *     (c) 2006 Pavel Charvat <pchar@ucw.cz>
- *     (c) 2007--2008 Martin Mares <mj@ucw.cz>
+ *     (c) 2007--2012 Martin Mares <mj@ucw.cz>
  *
  *     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 <string.h>
+
 #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);
+}
index 935da33b7c3f2f5f21f3bcfa0f0237608d321573..8cfe164501060d5aee8482a3d9fb0f85bf211e8e 100644 (file)
@@ -2,7 +2,7 @@
  *     UCW Library -- String Routines
  *
  *     (c) 2006 Pavel Charvat <pchar@ucw.cz>
- *     (c) 2007--2008 Martin Mares <mj@ucw.cz>
+ *     (c) 2007--2012 Martin Mares <mj@ucw.cz>
  *
  *     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);