C strstr() Function
The strstr()
function in C is used to find the first occurrence of a substring in a string. It returns a pointer to the first occurrence of the substring in the string. If the substring is not found, it returns NULL
.
Syntax of strstr()
The syntax of the strstr()
function is as follows:
Syntax:
char *strstr(const char *haystack, const char *needle);
The function takes two arguments:
- haystack: A pointer to the null-terminated string in which to search.
- needle: A pointer to the null-terminated substring to be located within the haystack.
The function returns a pointer to the first occurrence of the substring (needle) within the string (haystack). If the substring is not found, it returns NULL
.
Example of strstr() Function
Here is an example demonstrating how the strstr()
function works. The function will search for a substring within a string and return the location of its first occurrence.
Example:
#include <stdio.h>>
#include <string.h>
// For strstr function
int main()
{
const char *str = "Hello, world! Welcome to C programming.";
const char *subStr = "world";
// Find the first occurrence of 'world' in the string
char *result = strstr(str, subStr);
if (result) {
printf("Substring '%s' found at position: %ld\n", subStr, result - str);
} else {
printf("Substring '%s' not found.\n", subStr);
}
return 0;
}
Output:
Substring 'world' found at position: 7
Explanation of the Example
In this example:
- The strstr() function is used to locate the first occurrence of the substring "world" in the string "Hello, world! Welcome to C programming.".
- If the substring is found, the program prints the position of its first occurrence. The position is calculated as the difference between the pointer to the substring and the pointer to the beginning of the main string.
- If the substring is not found, the function returns NULL, and the program prints a message indicating that the substring was not found.
Important Notes
- The strstr()function is case-sensitive. It will not match substrings with different capitalization.
- If the needle is an empty string, the function will return the haystack string itself.
- If the haystack does not contain the needle, the function will return NULL.
- The function performs a linear search, so the time complexity is O(n), where n is the length of the haystack.