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:

  1. Include the necessary header file: c #include <string.h>

  2. Declare the string variables: c char *string = "This is a sample string"; char *substring = "sample";

  3. Use the strstr function to find the substring: c char *result = strstr(string, substring);

  4. The strstr function takes two arguments: the string to search in (string) and the substring to search for (substring).

  5. It returns a pointer to the first occurrence of the substring in the string, or NULL if the substring is not found.

  6. Check the result: c if (result != NULL) { printf("Substring found at index: %ld\n", result - string); } else { printf("Substring not found\n"); }

  7. If the result is not NULL, it means the substring was found in the string.

  8. The index of the substring within the string can be calculated by subtracting the starting address of the string from the result pointer.
  9. 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.