Created
March 4, 2011 17:20
-
-
Save jehiah/855214 to your computer and use it in GitHub Desktop.
strnchr because it doesn't exist for some reason
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
#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; | |
} |
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.
} while (++str <= end);
which should be "++str < end"
otherwise strnchr("abcd", 3, "d") returns "d"..
@dengzhp: I'm pretty sure strnchr("abcd", 3, "d")
is not allowed by the language.
*str == c
should be *str == character
, get rid of the silly line #17.
memchr()
is a thing 😉
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it's buggy
strnchr("abc", 3, 'a') returns NULL...