Is there a strchr with boundary?
There is not a standard library solution that mimics strchr() with a size limit.
Easy enough to code one though.
Loop termination
To form a strnchr(const char* ptr, int ch, size_t size) obliges a loop to stop on one of 3 cases:
Common mistakes:
Compare using ch and not the correct (char) ch.
Special consideration when ch == 0. strchr(s, 0) returns a pointer to the null character.
Special consideration when size == 0. A return of NULL is expected, not UB.
Using int size and not size_t.
Using char *ptr and not const char *ptr.
Direct implementation:
char *strnchr(const char* ptr, int ch, size_t size) {
while (size > 0) {
size--;
if (*ptr == (char) ch) {
return ptr;
}
if (*ptr == '\0') {
break;
}
ptr++;
}
return NULL;
}
Efficiency
Let len = length of string (unbounded if not exist), m = match offset (unbounded if not exist),
This solution is O(min(len, m, size)). Other posted solutions are are O(min(m, max(len, size)), O(min(len, m, size)), O(min(len, m) with UB), O(min(m, size) with UB).
Get correct functionality first, then optimize.
I'll leave optimization ideas for others.
Reference: strchr()
The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.
The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.