Welcome to this comprehensive guide on the C strrchr() function! We're glad to have you here at CodeYourCraft, your go-to place for learning programming. Today, we'll delve into one of the useful string functions in C ā strrchr().
strrchr() Functionstrrchr() is a built-in C library function that allows you to find the last occurrence of a specific character in a string. It returns a pointer to the last occurrence or a null pointer if the character is not found.
The syntax for strrchr() function is as follows:
char *strrchr(const char *str, int c);str: This is the string in which we want to find the character.c: This is the character that we are looking for in the string.š” Pro Tip: Remember, strrchr() function returns a pointer to the last occurrence of the character in the string, not the character itself.
Let's consider a simple example to demonstrate how the strrchr() function works:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *last_occurrence = strrchr(str, 'l');
printf("The last occurrence of 'l' is: %s\n", last_occurrence);
return 0;
}In the above example, we have a string str that contains "Hello, World!". We search for the last occurrence of the character 'l' and store the result in the last_occurrence pointer. Finally, we print the last occurrence of the character 'l'.
When you run the program, it will output:
The last occurrence of 'l' is: lo
š Note: The strrchr() function considers both uppercase and lowercase characters as different. For example, if you search for 'L' in the above string, it will not find any match.
You can also use the strrchr() function to check if a string contains a specific character. Here's an example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *last_occurrence = strrchr(str, '!' );
if (last_occurrence != NULL) {
printf("The string contains '!'\n");
} else {
printf("The string does not contain '!'\n");
}
return 0;
}In this example, we check if the string str contains the character '!'. If the last_occurrence pointer is not null, it means the character is found, and we print "The string contains '!'". Otherwise, we print "The string does not contain '!'".
When you run the program, it will output:
The string contains '!'
What does the `strrchr()` function return in C?
By the end of this lesson, you should have a good understanding of the strrchr() function and how to use it in your C programs. Keep practicing, and happy coding! šÆ