How to search for a string in C language?

In the C language, you can use the library function strstr to search for a string. The prototype of the strstr function is as follows:

char *strstr(const char *haystack, const char *needle);

In this case, haystack represents the string to search, while needle represents the string to find. The strstr function searches for the first occurrence of needle within haystack and returns a pointer to that position. If the needle is not found, it returns NULL.

Here is a sample code:

#include<stdio.h>
#include<string.h>

int main() {
    const char *haystack = "Hello, world!";
    const char *needle = "world";
    char *result = strstr(haystack, needle);
    
    if (result != NULL) {
        printf("Found at position: %ld\n", result - haystack);
    } else {
        printf("Not found\n");
    }
    
    return 0;
}

The output result is:

Found at position: 7

This indicates that the substring “world” appears at position 7 in the string “Hello, world!”

bannerAds