write a c program to finding substring in main string

27 Sep 2022 Balmiki Mandal 0 C Programming

In C, you can use the strstr function from the string.h header file to find a substring in a main string. The strstr function searches for the first occurrence of a substring in a string and returns a pointer to the start of that substring, or NULL if the substring is not found.

Here's an example of how to use strstr to find a substring in a main string:

write a c program to finding the substring in the main string

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

int main() {
    char main_str[] = "This is a main string.";
    char sub_str[] = "main";
    char *result = strstr(main_str, sub_str);

    if (result == NULL) {
        printf("'%s' is not found in '%s'\n", sub_str, main_str);
    } else {
        printf("'%s' is found in '%s' at position %ld\n", sub_str, main_str, result - main_str);
    }

    return 0;
}

In this example, the main string is "This is a main string." and the substring we're looking for is "main". The strstr function is used to search for the substring in the main string. If the substring is found, strstr returns a pointer to the start of the substring within the main string. The program then calculates the position of the substring in the main string by subtracting the start address of the main string from the start address of the substring. If the substring is not found, strstr returns NULL and the program outputs a message indicating that the substring was not found.

When run, the output of the program should be:

'main' is found in 'This is a main string.' at position 10

Note that strstr performs a case-sensitive search. If you need a case-insensitive search, you can use the strcasestr function instead.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.