strrchr() Function
The strrchr()
function in C locates the last occurrence of a specific character within a string. It returns a pointer to that occurrence, allowing you to determine the position of the character from the end of the string. Additionally, since the terminating null-character is considered part of the string, this function can be used to obtain a pointer to the end of the string.
Syntax of strrchr()
const char *strrchr(const char *str, int character);
Parameters
Parameter | Description |
---|---|
str | C string in which to search for the character. |
character | The character to be located. It is passed as an int but converted internally to char. |
Return Value
The function returns a pointer to the last occurrence of the specified character within the given string. If the character is not found, it returns a null pointer.
Note that the terminating null-character is considered part of the string. Thus, searching for '\0'
will yield a pointer to the end of the string. This behavior can be useful for determining string lengths or for appending characters.
Examples for strrchr()
Example 1: Finding the Last Occurrence of a Character
This example demonstrates how to locate the last occurrence of a character within a string using strrchr()
.
Program
#include <stdio.h>
#include <string.h>
int main() {
const char *text = "hello world";
const char *ptr = strrchr(text, 'l');
if (ptr != NULL) {
printf("Last occurrence of 'l': %s\n", ptr);
} else {
printf("Character not found.\n");
}
return 0;
}
Output:
Last occurrence of 'l': ld
Example 2: Character Not Found
This example shows the case where the specified character does not exist in the string, resulting in a null pointer.
Program
#include <stdio.h>
#include <string.h>
int main() {
const char *text = "example";
const char *ptr = strrchr(text, 'z');
if (ptr != NULL) {
printf("Last occurrence of 'z': %s\n", ptr);
} else {
printf("Character not found.\n");
}
return 0;
}
Output:
Character not found.
Example 3: Locating the Null Terminator
This example demonstrates that searching for the null character returns a pointer to the end of the string.
Program
#include <stdio.h>
#include <string.h>
int main() {
const char *text = "Find end";
const char *ptr = strrchr(text, '\0');
// ptr points to the terminating null character; printing it results in an empty string.
printf("Pointer to null terminator: %s\n", ptr);
return 0;
}
Output:
Pointer to null terminator: