Featured Post

Trie implementation in C

Find if a substring exists in a string?

This is a simple implementation of function which determines if a substring exists in a string or not. Also it determines how many times the the substring is present in a string.

#include<stdio.h>
#include <string.h>
int main()
{

    int i=0,j=0,k=0,count=0,l=0,k1=0;
    char a[80],b[80];

    printf("\nEnter main string:-\n");
    scanf("%[^\n]",&a);
    getchar(); //To Flush '\n'
    printf("\nEnter sub-string:-\n");
    scanf("%[^\n]",&b);

    l=strlen(b);

    while (a[i]!=EOF)
    {
        if (a[i]==b[j])
        {
            i++;
            j++;
            k1=1;

            if (j==l)
            {
                j=0;
                k=1;
                count=count+1;
            }
        }
        else
        {
            if (k1==1)
            {
                j=0;
                k1=0;
            }
            else
                i++;
        }
    }

    if (k==1)
    {
        printf("\n\nThe given sub-string is present in the main string.");
        printf("\nIt is present %d times.",count);
    }

    else
    {
        if (k==0)
            printf("\n\nThe given sub-string is not present in the main string.");
    }

}

Comments