Skip to content

Instantly share code, notes, and snippets.

@SourLemonJuice
Created September 22, 2024 06:06
Show Gist options
  • Save SourLemonJuice/c5d3ece14119b443ea83659d5e769022 to your computer and use it in GitHub Desktop.
Save SourLemonJuice/c5d3ece14119b443ea83659d5e769022 to your computer and use it in GitHub Desktop.
A strnstr() function in C. I was going to use this: https://stackoverflow.com/a/25705264/25416550, but its "n" start with "needle". So I implemented my own version
// This is free and unencumbered software released into the public domain.
/*
Search "needle" in "haystack", limited to the first "len" chars of haystack
*/
char *strnstr(char haystack[const restrict static 1], char needle[const restrict static 1], int len)
{
if (len <= 0)
return NULL;
char *temp_str;
int needle_len = strlen(needle);
while (true) {
temp_str = strchr(haystack, needle[0]);
if (temp_str == NULL)
return NULL;
if ((temp_str - haystack) + needle_len > len)
return NULL;
if (strncmp(temp_str, needle, needle_len) == 0)
return temp_str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment