strrchr() in C
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 program to illustrate
// the strrchr() function
#include <stdio.h>
#include <string.h>
int main()
{
// initializing string
char str[] = "GeeksforGeeks";
// character to be searched
char chr = 'k';
// Storing pointer returned by
char* ptr = strrchr(str, chr);
// getting the position of the character
if (ptr) {
printf("Last occurrence of %c in %s is at index %d",
chr, str, ptr - str);
}
// condition for character not present
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 program to illustrate
// the strrchr() function
#include <stdio.h>
#include <string.h>
int main()
{
// creating some string
char str[] = "GeeksforGeeks";
char* ptr;
// The character to be searched
char chr = 'z';
// pointer returned by strrchr()
ptr = strrchr(str, chr);
// ptr-string gives the index location
if (ptr) {
printf("Last occurrence of %c in %s is at %d", chr,
str, ptr - str);
}
// If the character we're searching is not present in
// the array
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.