Skip to content
Laviyx Learn

Try

DS Lab · Experiment 18

Boyer-Moore pattern matching

CPattern matchingJNTUH R22 · CS306PC

Aim

To write a C program that finds every occurrence of a pattern in a text using the Boyer-Moore algorithm with the bad character heuristic, printing the bad character table, each alignment tried, and the positions where the pattern is found.

Algorithm

  1. Read the text (length n) and the pattern (length m).
  2. Build the bad character table: for every character, last[c] is the index of its last occurrence in the pattern, or −1 if it does not occur.
  3. Place the pattern at shift s = 0 (pattern under text[0..m-1]).
  4. While s ≤ n − m: compare the pattern with the text from right to left, starting at j = m − 1, while the characters match.
  5. If all characters matched (j < 0), report a match at index s. Shift by m − last[text[s + m]] if there is a character after this window, otherwise by 1.
  6. If there was a mismatch at j with text character c, shift the pattern by j − last[c] so that the last c in the pattern lines up with the text, but always by at least 1.
  7. Print the number of matches.

Program

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

#define MAX_TEXT 200
#define MAX_PATTERN 50
#define NO_OF_CHARS 256

/* Read one line into buf and remove the newline */
int read_line(const char *prompt, char *buf, int size) {
    printf("%s", prompt);
    if (fgets(buf, size, stdin) == NULL) {
        return 0;
    }
    buf[strcspn(buf, "\n")] = '\0';
    return 1;
}

int max(int a, int b) {
    return a > b ? a : b;
}

void build_bad_char_table(const char *pat, int m, int last[]) {
    for (int c = 0; c < NO_OF_CHARS; c++) {
        last[c] = -1;
    }
    for (int i = 0; i < m; i++) {
        last[(unsigned char)pat[i]] = i;    /* later positions overwrite earlier ones */
    }
}

int boyer_moore(const char *text, int n, const char *pat, int m, const int last[]) {
    int s = 0, matches = 0;
    while (s <= n - m) {
        int j = m - 1;
        while (j >= 0 && pat[j] == text[s + j]) {   /* compare right to left */
            j--;
        }
        if (j < 0) {
            printf("s = %2d: match found at index %d", s, s);
            matches++;
            int shift = (s + m < n) ? m - last[(unsigned char)text[s + m]] : 1;
            printf(", shift %d\n", shift);
            s += shift;
        } else {
            char c = text[s + j];
            int shift = max(1, j - last[(unsigned char)c]);
            printf("s = %2d: mismatch at pattern[%d], text has '%c', shift %d\n",
                   s, j, c, shift);
            s += shift;
        }
    }
    return matches;
}

int main(void) {
    char text[MAX_TEXT], pat[MAX_PATTERN];
    int last[NO_OF_CHARS];

    if (!read_line("Enter the text: ", text, MAX_TEXT) ||
        !read_line("Enter the pattern: ", pat, MAX_PATTERN)) {
        printf("Invalid input\n");
        return 1;
    }
    int n = (int)strlen(text);
    int m = (int)strlen(pat);
    if (m == 0 || m > n) {
        printf("The pattern must be non-empty and not longer than the text\n");
        return 1;
    }

    build_bad_char_table(pat, m, last);
    printf("\nBad character table (last index of each pattern character):\n");
    for (int i = 0; i < m; i++) {
        if (strchr(pat, pat[i]) == pat + i) {   /* print each character once */
            printf("  '%c' : %d\n", pat[i], last[(unsigned char)pat[i]]);
        }
    }
    printf("  any other character : -1\n\n");

    int matches = boyer_moore(text, n, pat, m, last);
    if (matches == 0) {
        printf("\nPattern not found\n");
    } else {
        printf("\nPattern found %d time(s)\n", matches);
    }
    return 0;
}

Output

Pattern occurs twice

Output 1
Enter the text: THIS IS A TEST TEXT TO TEST
Enter the pattern: TEST

Bad character table (last index of each pattern character):
  'T' : 3
  'E' : 1
  'S' : 2
  any other character : -1

s =  0: mismatch at pattern[3], text has 'S', shift 1
s =  1: mismatch at pattern[3], text has ' ', shift 4
s =  5: mismatch at pattern[3], text has 'A', shift 4
s =  9: mismatch at pattern[3], text has 'S', shift 1
s = 10: match found at index 10, shift 5
s = 15: mismatch at pattern[2], text has 'X', shift 3
s = 18: mismatch at pattern[3], text has 'O', shift 4
s = 22: mismatch at pattern[3], text has 'S', shift 1
s = 23: match found at index 23, shift 1

Pattern found 2 time(s)

Pattern not present

Output 2
Enter the text: DATA STRUCTURES LAB
Enter the pattern: TREE

Bad character table (last index of each pattern character):
  'T' : 0
  'R' : 1
  'E' : 3
  any other character : -1

s =  0: mismatch at pattern[3], text has 'A', shift 4
s =  4: mismatch at pattern[3], text has 'R', shift 2
s =  6: mismatch at pattern[3], text has 'C', shift 4
s = 10: mismatch at pattern[2], text has 'R', shift 1
s = 11: mismatch at pattern[3], text has 'S', shift 4
s = 15: mismatch at pattern[3], text has 'B', shift 4

Pattern not found

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

Index positions start at 0. This program uses only the bad character rule. The full Boyer-Moore algorithm also has a good suffix rule and takes the larger of the two shifts; the bad character rule alone is enough to show the main idea and is what most lab records implement.

The idea: comparing from the right end lets one mismatch skip many positions. In the first run, a mismatch on a space or on 'A', which do not occur in "TEST", moves the pattern 4 places at once. Count the alignments: the algorithm tries 9 positions, while a simple search that moves one place at a time would try all 24.

fgets is used instead of scanf("%s") so that the text can contain spaces.

Common mistakes

  • Comparing the pattern from left to right. Boyer-Moore compares from the last character of the pattern; that is what makes the large shifts possible.

  • Allowing a zero or negative shift when the mismatched character occurs later in the pattern than j. The shift must be at least 1, otherwise the loop never ends.

  • Using a plain char as an array index. Characters above 127 can be negative on some compilers; cast to unsigned char first.

  • Reading the text with scanf("%s", ...), which stops at the first space.

Viva questions

Try to answer each one aloud before you open it.

  • What is the main idea of the Boyer-Moore algorithm?

    It compares the pattern with the text from right to left. When a mismatch happens, it uses information about the pattern to shift it forward by more than one position whenever possible.

  • What is the bad character heuristic?

    On a mismatch with text character c, shift the pattern so that the last occurrence of c in the pattern lines up with that text character. If c does not occur in the pattern, move the pattern completely past it.

  • What is the good suffix heuristic?

    When some characters at the end matched before the mismatch, shift the pattern so that another occurrence of that matched part (or a matching prefix) lines up with it. Full Boyer-Moore uses the larger of the two shifts.

  • What is the time complexity of Boyer-Moore?

    With only the bad character rule the worst case is O(nm), for example on text like 'AAAA...' and pattern 'AAA'. In practice, on normal text, it is very fast and often looks at fewer than n characters.

  • When does Boyer-Moore work best?

    When the alphabet is large and the pattern is fairly long, as in ordinary English text, because mismatched characters are often not in the pattern and allow big jumps.

Learn the concepts

All Data Structures Lab experiments →