Skip to content

Commit

Permalink
Add strstr to string.h
Browse files Browse the repository at this point in the history
  • Loading branch information
maximecb committed Oct 1, 2023
1 parent 5edeb07 commit 563ab08
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
28 changes: 26 additions & 2 deletions ncc/include/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,34 @@ char* strchr(char *str, int c)
return NULL;
}

// TODO:
// Returns a pointer to the first occurrence of str2 in str1,
// or a null pointer if str2 is not part of str1.
// char* strstr(char * str1, const char * str2);
char* strstr(char* s1, char* s2)
{
char* p1 = s1;
char* p2;

while (*s1)
{
p2 = s2;

while (*p2 && (*p1 == *p2))
{
++p1;
++p2;
}

if (!*p2)
{
return (char*)s1;
}

++s1;
p1 = s1;
}

return NULL;
}

// TODO:
// char* strncpy(char* destination, const char* source, size_t num)
Expand Down
13 changes: 11 additions & 2 deletions ncc/tests/strings.c
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,19 @@ int main()

// strchr
char* str = "lestring";
assert(strchr("", 'c') == null);
assert(strchr("c", 'c') != null);
assert(strchr("", 'c') == NULL);
assert(strchr("c", 'c') != NULL);
assert(strchr(str, 's') == str + 2);

// strstr
char* s = "abcabcabcdabcde";
assert(strstr(s, "x") == NULL);
assert(strstr(s, "xyz") == NULL);
assert(strstr(s, "a") == s + 0);
assert(strstr(s, "abc") == s + 0);
assert(strstr(s, "abcd") == s + 6);
assert(strstr(s, "abcde") == s + 10);

// memset
memset(arr, 177, 19);
assert(arr[0] == 177);
Expand Down

0 comments on commit 563ab08

Please sign in to comment.