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;
}
@jehiah
Copy link
Author

jehiah commented Apr 25, 2011

thanks @frgg the increment did happen in the wrong spot making it unable to find characters in position[0]. I've updated the code with a fix for that.

@stattrak-dragonlore
Copy link

} while (++str <= end);  

which should be "++str < end"

otherwise strnchr("abcd", 3, "d") returns "d"..

@nitrix
Copy link

nitrix commented Jun 24, 2014

@dengzhp: I'm pretty sure strnchr("abcd", 3, "d") is not allowed by the language.

@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