c strstr
The strstr
function in C is used to find the first occurrence of a substring within a string. It returns a pointer to the first occurrence of the substring in the string, or NULL
if the substring is not found.
Here is an explanation of each step involved in using the strstr
function:
Include the necessary header file:
c #include <string.h>
Declare the string variables:
c char *string = "This is a sample string"; char *substring = "sample";
Use the
strstr
function to find the substring:c char *result = strstr(string, substring);
The
strstr
function takes two arguments: the string to search in (string
) and the substring to search for (substring
).It returns a pointer to the first occurrence of the substring in the string, or
NULL
if the substring is not found.Check the result:
c if (result != NULL) { printf("Substring found at index: %ld\n", result - string); } else { printf("Substring not found\n"); }
If the result is not
NULL
, it means the substring was found in the string.- The index of the substring within the string can be calculated by subtracting the starting address of the string from the result pointer.
- If the result is
NULL
, it means the substring was not found in the string.
That's it! The strstr
function allows you to find the first occurrence of a substring within a string in C.