C Programming: strstr() Function 🎯

beginner
15 min

C Programming: strstr() Function 🎯

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.

What is the 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.

Syntax 📝

c
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.

Example 💡

Let's look at a simple example to better understand the strstr() function:

c
#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

Advanced Example 💡

Let's take our example a step further and demonstrate finding multiple occurrences of a substring:

c
#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

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `strstr()` function return if it doesn't find the specified substring in the `haystack`?

Happy coding! 💪🚀