From 245c7e7f49a86ad798dae6cbe92807c8447d1183 Mon Sep 17 00:00:00 2001 From: Andrew Bettison Date: Wed, 3 Oct 2012 17:13:45 +0930 Subject: [PATCH] Change str_str() to return (char*) not (const char*) Also rewrite implementation to handle edge cases, rename arguments to be more self documenting. --- str.c | 13 +++++++++---- str.h | 6 ++++-- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/str.c b/str.c index 9307cf0e..247e5ed2 100644 --- a/str.c +++ b/str.c @@ -46,10 +46,15 @@ int strcase_startswith(char *str, const char *substring, char **afterp) } /* Like strstr() but doesn't depend on null termination */ -const char *str_str(const char *s1,const char *s2,int s1len) +char *str_str(char *haystack, const char *needle, int haystack_len) { - int s2len=strlen(s2); - for(;*s1&&(s1len--);s1++) - if (!strncmp(s1,s2,s2len)) return s1; + size_t needle_len = strlen(needle); + if (needle_len == 0) + return haystack; + if (haystack_len >= needle_len) { + for (; *haystack && haystack_len >= needle_len; ++haystack, --haystack_len) + if (strncmp(haystack, needle, needle_len) == 0) + return haystack; + } return NULL; } diff --git a/str.h b/str.h index ee1c3f4d..c67ef6df 100644 --- a/str.h +++ b/str.h @@ -38,7 +38,9 @@ int str_startswith(char *str, const char *substring, char **afterp); int strcase_startswith(char *str, const char *substring, char **afterp); /* like strstr(), but doesn't depend on null termination. - @author Paul Gardner-Stephen */ -const char *str_str(const char *s1,const char *s2,int s1len); + @author Paul Gardner-Stephen + @author Andrew Bettison + */ +char *str_str(char *haystack, const char *needle, int haystack_len); #endif