From 7137c20ed1f486f31047a3a3dc77d90d0a5bb7dc Mon Sep 17 00:00:00 2001 From: Michael Brown Date: Sun, 8 Jul 2007 22:03:12 +0100 Subject: Add strcspn() and strndup() --- src/core/string.c | 45 +++++++++++++++++++++++++++++++++++++++++---- src/include/string.h | 2 ++ 2 files changed, 43 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/core/string.c b/src/core/string.c index 353abd6f..87c50570 100644 --- a/src/core/string.c +++ b/src/core/string.c @@ -279,6 +279,31 @@ size_t strspn(const char *s, const char *accept) } #endif +#ifndef __HAVE_ARCH_STRCSPN +/** + * strcspn - Calculate the length of the initial substring of @s which only + * contain letters not in @reject + * @s: The string to be searched + * @accept: The string to search for + */ +size_t strcspn(const char *s, const char *reject) +{ + const char *p; + const char *r; + size_t count = 0; + + for (p = s; *p != '\0'; ++p) { + for (r = reject; *r != '\0'; ++r) { + if (*p == *r) + return count; + } + ++count; + } + + return count; +} +#endif + #ifndef __HAVE_ARCH_STRPBRK /** * strpbrk - Find the first occurrence of a set of characters @@ -541,9 +566,21 @@ void * memchr(const void *s, int c, size_t n) #endif -char * strdup(const char *s) { - char *new = malloc(strlen(s)+1); - if (new) - strcpy(new,s); +char * strndup(const char *s, size_t n) +{ + size_t len = strlen(s); + char *new; + + if (len>n) + len = n; + new = malloc(len+1); + if (new) { + new[len] = '\0'; + memcpy(new,s,len); + } return new; } + +char * strdup(const char *s) { + return strndup(s, ~((size_t)0)); +} diff --git a/src/include/string.h b/src/include/string.h index e02b5edb..1d104c52 100644 --- a/src/include/string.h +++ b/src/include/string.h @@ -30,6 +30,7 @@ char * strrchr(const char * s, int c); size_t strlen(const char * s); size_t strnlen(const char * s, size_t count); size_t strspn(const char *s, const char *accept); +size_t strcspn(const char *s, const char *reject); char * strpbrk(const char * cs,const char * ct); char * strtok(char * s,const char * ct); char * strsep(char **s, const char *ct); @@ -41,6 +42,7 @@ void * memscan(void * addr, int c, size_t size); char * strstr(const char * s1,const char * s2); void * memchr(const void *s, int c, size_t n); char * strdup(const char *s); +char * strndup(const char *s, size_t n); extern const char * strerror ( int errno ); -- cgit v1.2.3-55-g7522