strstr() function in C
The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is used to return substring from first match till the last character.Syntax:
cchar *strstr(const char *haystack, const char *needle);
a. haystack: This is a pointer to the null-terminated string to be searched.b. needle: This is a pointer to the null-terminated string containing the sequence of characters to match.
The function returns a pointer to the first occurrence of the substring needle in the string haystack. If the substring is not found, it returns a null pointer.
Example
c#include <stdio.h>
#include <string.h>
int main() {
const char *haystack = "Hello, World! This is a simple example.";
const char *needle = "World";
char *result = strstr(haystack, needle);
if (result != NULL) {
printf("'%s' found at position %ld in '%s'\n", needle, result - haystack, haystack);
} else {
printf("'%s' not found in '%s'\n", needle, haystack);
}
return 0;
}
In this example, strstr() is used to search for the substring "World" in the string "Hello, World! This is a simple example." If the substring is found, it prints its position; otherwise, it prints a message indicating that the substring was not found.
0 Comments