ADVERTISEMENT
ADVERTISEMENT

C program to check whether a substring is present in a given string

In this program, we will learn how to check whether a substring is present in a string or not without using library function?

We are implementing a function named myStrStr() this function will return 1 if substring present in the string and return 0, if substring is not present in the string.

Program to check substring in a string in C

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

//function declaration
int myStrStr(char* str, char* sub);

int main()
{
    char str[100] = { 0 };
    char strTocheck[10] = { 0 };

    printf("Enter complete string: ");
    scanf("%[^\n]s", str);
    getchar();

    printf("Enter string to check: ");
    scanf("%[^\n]s", strTocheck);

    if (myStrStr(str, strTocheck))
        printf("String \"%s\" found in \"%s\"\n", strTocheck, str);
    else
        printf("String \"%s\" not found in \"%s\"\n", strTocheck, str);

    return 0;
}

//function definition
int myStrStr(char* str, char* sub)
{
    int flag = 0;

    int i = 0, len1 = 0, len2 = 0;

    len1 = strlen(str);
    len2 = strlen(sub);

    while (str[i] != '\0') {
        if (str[i] == sub[0]) {
            if ((i + len2) > len1)
                break;

            if (strncmp(str + i, sub, len2) == 0) {
                flag = 1;
                break;
            }
        }
        i++;
    }

    return flag;
}

Output

First run:
Enter complete string: Hello how are you?
Enter string to check: how
String "how" found in "Hello how are you?"

Second run:
Enter complete string: Hello how are you?
Enter string to check: we
String "we" not found in "Hello how are you?"

Third run:
Enter complete string: Hello how are you?
Enter string to check: how are you?
String "how are you?" found in "Hello how are you?"

C Strings User-defined Functions Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.