Skip to content

Instantly share code, notes, and snippets.

@jehiah
Created March 4, 2011 17:20
Show Gist options
  • Save jehiah/855214 to your computer and use it in GitHub Desktop.
Save jehiah/855214 to your computer and use it in GitHub Desktop.
strnchr because it doesn't exist for some reason
#include <stdlib.h>
/*
Returns a pointer to the first occurrence of character in the C string str.
The terminating null-character is considered part of the C string. Therefore,
it can also be located to retrieve a pointer to the end of a string.
@param str the string to be searched
@param len the number of characters to search
@param character the character to search for
@returns A pointer to the first occurrence of character in str.
If the value is not found, the function returns a null pointer.
*/
const char *strnchr(const char *str, size_t len, int character) {
const char *end = str + len;
char c = (char)character;
do {
if (*str == c) {
return str;
}
} while (++str <= end);
return NULL;
}
@nitrix
Copy link

nitrix commented Jun 24, 2014

*str == c should be *str == character, get rid of the silly line #17.

@benpicco
Copy link

benpicco commented Sep 8, 2021

memchr() is a thing 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment