Saturday 11 November 2017

C Program to Implement the KMP Pattern Searching Algorithm


Code:

#include
#include
#include

int main()
{
    char string[100], matchcase[20], c;
    int i = 0, j = 0, index;

    /*Scanning string*/
    printf("Enter string: ");
    do
    {
        fflush(stdin);
        c = getchar();
        string[i++] = tolower(c);

    } while (c != '\n');
    string[i - 1] = '\0';
    /*Scanning substring*/
    printf("Enter substring: ");
    i = 0;
    do
    {
        fflush(stdin);
        c = getchar();
        matchcase[i++] = tolower(c);
    } while (c != '\n');
    matchcase[i - 1] = '\0';
    for (i = 0; i < strlen(string) - strlen(matchcase) + 1; i++)
    {
        index = i;
        if (string[i] == matchcase[j])
        {
            do
            {
                i++;
                j++;
            } while(j != strlen(matchcase) && string[i] == matchcase[j]);
            if (j == strlen(matchcase))
            {
                printf("Match found from position %d to %d.\n", index + 1, i);
                return 0;
            }
            else
            {
                i = index + 1;
                j = 0;
            }
        }
    }
    printf("No substring match found in the string.\n");

    return 0;
}


Output:

Enter string: programming
Enter substring: gram
Match found from position 4 to 7.


More C programs














100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...