Search for a character in a string using strchr, strrchr

Опубликовано: 18 Февраль 2026
на канале: Programming with Sikander
790
13

This video lecture explains how to utilize the C String Library function to search for a character in a given string.
The library functions are strchr and strrchr.
The strchr() function returns a pointer to the first occurrence of the character c in the string s.

The strrchr() function returns a pointer to the last occurrence of the character c in the string s.

Return Value :
The strchr() and strrchr() functions return a pointer to the matched character or NULL if the character is not found. The terminating null byte is considered part of the string, so that if c is specified as '\0', these functions return a pointer to the terminator.

Code : (Include the required header files)

int main() {
char data[] = "sikandar";
char key = 'a';

char *ptr = strchr( data , key);
if( ptr == NULL)
printf("Key character not present \n");
else{
int index = ptr - data;
printf("Character at index %d \n", index);
printf("ptr = %p %s \n",ptr, ptr);
}
return 0;
}
#cprogramming #cinterviewquestions #cstrings