C Language strchr() Function: Finding the First Occurrence of a Character in a String

Header file: #include <string.h>

strchr() is used to find the first occurrence of a character in a string, and its prototype is as follows:

char * strchr (const char *str, int c);

【Parameters】str is the string to be searched, and c is the character to be searched for.

strchr() will find the address of the first occurrence of character c in the string str and return that address.

Note: The NUL termination character of the string str is also included in the search range, so the character after the last character of str can also be located.

【Return Value】If the specified character is found, the address of that character is returned; otherwise, NULL is returned.

The returned address can be understood as the randomly allocated address of the string in memory plus the position of the character you are searching for. If the character first appears at position i in the string, then the returned address can be understood as str + i.

Tip: If you want to find the last occurrence of a character in a string, you can use the strrchr() function.

【Example】Finding the first occurrence of character ‘5’.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){    char *s = "0123456789012345678901234567890";    char *p,*q;    unsigned char tmp;    p = strchr(s, '5');    printf("Original string:%s\n", s);    printf("String after 5:%s\n", p);
    tmp = (unsigned char)(strchr(s, '5')-s);    q = (tmp > 0)?strndup(s, tmp):strdup(s);    printf("String before 5:%s\n", q);    return 0; }

Running Result:

book@ubuntu:/home/linux_c/has_arg$ ./strchr1

Original string:0123456789012345678901234567890

String after 5:56789012345678901234567890

String before 5:01234

Leave a Comment