Change str_str() to return (char*) not (const char*)

Also rewrite implementation to handle edge cases, rename arguments to be more
self documenting.
This commit is contained in:
Andrew Bettison 2012-10-03 17:13:45 +09:30
parent 46f81d9d2e
commit 245c7e7f49
2 changed files with 13 additions and 6 deletions

13
str.c
View File

@ -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;
}

6
str.h
View File

@ -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 <paul@servalproject.org> */
const char *str_str(const char *s1,const char *s2,int s1len);
@author Paul Gardner-Stephen <paul@servalproject.org>
@author Andrew Bettison <andrew@servalproject.com>
*/
char *str_str(char *haystack, const char *needle, int haystack_len);
#endif