searching string and printing logic strstr logic
The strstr function in C is used to search for a substring (a sequence of characters) within a larger string. It returns a pointer to the first occurrence of the substring within the string, or NULL if the substring is not found.
Here's an example of how the strstr function can be used to search for a substring in a string:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "The quick brown fox jumps over the lazy dog";
char substr[] = "brown";
char *result = strstr(str, substr);
if (result != NULL) {
printf("Substring found at position %ld\n", result - str);
} else {
printf("Substring not found\n");
}
return 0;
}
In this example, the strstr function is used to search for the substring "brown" in the string "The quick brown fox jumps over the lazy dog". The result is a pointer to the first occurrence of the substring within the string, which is then used to calculate the position of the substring within the string. If the substring is not found, the strstr function returns NULL and the program outputs "Substring not found".
The result - str expression calculates the index of the substring within the string by subtracting the address of the start of the string (str) from the address of the start of the substring (result). This gives the number of characters between the start of the string and the start of the substring.
Note that strstr is case-sensitive, meaning that it will only match substrings that have the same case as the characters in the string being searched. If case-insensitive matching is required, the strcasestr function can be used instead.