Welcome to a comprehensive guide on the strstr() function in C programming! In this tutorial, we will explore this useful tool, understanding its purpose, syntax, and practical applications. By the end, you'll be able to find a specific substring within a string with ease.
strstr() function? 📝The strstr() function is a built-in function in C that returns a pointer to the first occurrence of a substring in a given string, or a null pointer if no match is found. It's an essential tool for string manipulation in C programming.
char *strstr(const char *haystack, const char *needle);haystack: The string in which we're searching for the substring.needle: The substring we're trying to find in the haystack.Let's look at a simple example to better understand the strstr() function:
#include <stdio.h>
#include <string.h>
int main() {
char haystack[] = "Hello, World!";
char needle[] = "World";
char *result = strstr(haystack, needle);
if (result != NULL) {
printf("Found substring: %s\n", result);
} else {
printf("Substring not found.\n");
}
return 0;
}In this example, we have a string haystack with the value "Hello, World!". We're searching for the substring "World" using the strstr() function and storing the result in the variable result. The output will be:
Found substring: World
Let's take our example a step further and demonstrate finding multiple occurrences of a substring:
#include <stdio.h>
#include <string.h>
int main() {
char haystack[] = "Hello, World! Hello, again, World!";
char needle[] = "World";
char *start = haystack;
char *result;
while ((result = strstr(start, needle)) != NULL) {
printf("Found substring at position: %d\n", result - haystack + 1);
start = result + strlen(needle);
}
return 0;
}In this example, we have a string haystack containing multiple occurrences of the substring "World". Our code loops through the string, finding each occurrence and printing its position within the original string. The output will be:
Found substring at position: 6
Found substring at position: 20
What does the `strstr()` function return if it doesn't find the specified substring in the `haystack`?
Happy coding! 💪🚀