Created
September 22, 2024 06:06
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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