Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a strchr with boundary?

Tags:

c++

c

string

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.

like image 541
a_girl Avatar asked Aug 19 '21 16:08

a_girl


People also ask

What is the difference between Memchr and Strchr?

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.

What does Strchr return if not found?

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.

Is the use of function char * Strchr CH c )?

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.

What is the use of Strchr?

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.


2 Answers

You can try:

void* memchr( const void* ptr, int ch, size_t count )

like image 177
a_girl Avatar answered Oct 23 '22 08:10

a_girl


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;
}
like image 26
Mad Physicist Avatar answered Oct 23 '22 08:10

Mad Physicist