Skip to content

Instantly share code, notes, and snippets.

@bentrevett
Created January 13, 2017 12:48
Show Gist options
  • Save bentrevett/c668766907d00c6acd0aa494fa746fe1 to your computer and use it in GitHub Desktop.
Save bentrevett/c668766907d00c6acd0aa494fa746fe1 to your computer and use it in GitHub Desktop.
Given string 'haystack', find if sub-string 'needle' exists.
char *strstr(const char *haystack, const char *needle)
{
size_t h_len = strlen(haystack);
size_t n_len = strlen(needle);
size_t i, j;
for (i = 0; i < h_len; i++)
{
size_t found = 0;
for (j = 0; j < n_len; j++)
{
if (i + n_len < h_len)
if (haystack[i + j] == needle[j])
found++;
}
if (found == n_len)
return &needle[i];
}
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment