There is a char *strchr( const char *str, int ch )
function defined in <string.h>
.
It has no boundary, after which it stops the search.
Is there a similar function somewhere, which you can pass a boundary to?
Edit:
I have a char* pos
and a length of a substring and I want to find a specific ASCII character in it, but I don't want it to search up to the very null-terminator, because I don't care for the second part of the character sequence.
Functionally there is no difference in that they both scan an array / pointer for a provided value. The memchr version just takes an extra parameter because it needs to know the length of the provided pointer. The strchr version can avoid this because it can use strlen to calculate the length of the string.
The strchr() function returns a pointer to the first occurrence of c that is converted to a character in string. The function returns NULL if the specified character is not found.
What is the use of function char *strchr(ch, c)? Explanation: The given code char *strchr(ch, c) return pointer to first occurrence of c in ch or NULL if not present.
Description. The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.
You can try:
void* memchr( const void* ptr, int ch, size_t count )
As the other answer points out, you can use memchr
, but you'll need to call it twice if you want to avoid going out of bounds:
char *strnchr(const char *s, int c, size_t n)
{
char *nul = memchr(s, 0, n);
if(!c) return nul;
if(nul) n = nul - s;
return memchr(s, c, n);
}
With the right hardware optimization, this may be more efficient than just checking the first n
characters:
char *strnchr(const char *s, int c, size_t n)
{
for(char *p = s; (p - s) < n; p++) {
if(*p == c) return p;
if(!*p) break;
}
return NULL;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With