Skip to content

Instantly share code, notes, and snippets.

@smarthall
Forked from jehiah/strnchr.c
Created February 28, 2012 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smarthall/1935568 to your computer and use it in GitHub Desktop.
Save smarthall/1935568 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment