Q:

C program to implement the KMP pattern search algorithm

belongs to collection: C String Programs

0

C program to implement the KMP pattern search algorithm

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Read a string from the user, then find the word in the string using the KMP pattern search algorithm, and print the index of the word within string on the console screen.

Program:

The source code to implement the KMP pattern search algorithm is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to implement the KMP pattern search algorithm

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

int main()
{
    char str[64];
    char word[20] = "is";

    int i = 0;
    int j = 0;
    int c = 0;

    int index = 0;
    int length = 0;

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

    while (str[i]) {
        str[i] = tolower(str[i]);
        i++;
    }

    length = strlen(str) - strlen(word) + 1;
    for (i = 0; i < length; i++) {
        index = i;
        if (str[i] == word[j]) {
            do {
                i++;
                j++;

            } while (j != strlen(word) && str[i] == word[j]);

            if (j == strlen(word)) {
                printf("Word '%s' found from index %d to %d.\n", word, index + 1, i);
                return 0;
            }
            else {
                i = index + 1;
                j = 0;
            }
        }
    }

    printf("No word found in the string.\n");

    return 0;
}

Output:

Enter string: This is india
Word 'is' found from index 3 to 4.

Explanation:

In the main() function, we read a string from the user and search a specific word within the string using the KMP search algorithm and printed the index of matched word in the string on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< C program to sort the words of the string...