The strrchr() function in C locates the last occurrence of a character in a string and returns a pointer to it. It is a standard library function defined inside <string.h> header file.
Syntax :
char* strrchr( char* str, int chr );
Parameter:
- str: specifies the pointer to the null-terminated string in which the search is to be performed.
- chr: specifies the character to be searched.
Return Value:
- The function returns a pointer to the last location of chr in the string if the chr is found.
- If chr is not found, it returns a null pointer.
Example:
C
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "GeeksforGeeks" ;
char chr = 'k' ;
char * ptr = strrchr (str, chr);
if (ptr) {
printf ( "Last occurrence of %c in %s is at index %d" ,
chr, str, ptr - str);
}
else {
printf ( "%c is not present in %s " , chr, str);
}
return 0;
}
|
Output
Last occurrence of k in GeeksforGeeks is at index 11
When the character is not present in the string
strrchr() function returns a NULL pointer if the searched character is not found in the given string.
Example:
C
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "GeeksforGeeks" ;
char * ptr;
char chr = 'z' ;
ptr = strrchr (str, chr);
if (ptr) {
printf ( "Last occurrence of %c in %s is at %d" , chr,
str, ptr - str);
}
else {
printf ( "%c is not present in %s " , chr, str);
}
return 0;
}
|
Output
z is not present Geeks for Geeks
Time Complexity: O(n),
Space Complexity: O(1),
where n is the length of the string.
Note: NULL character is also treated same as other character by strrchr() function, so we can also use it to find the end of the string.
Last Updated :
31 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...