If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C programming language, substring searching is the process of finding a specific sequence of characters (known as the substring) within a larger string (known as the text). There are various algorithms that can be used to perform substring searching, with different trade-offs in terms of performance and complexity.
One of the most commonly used algorithms for substring searching is the Knuth-Morris-Pratt (KMP) algorithm. It is based on the observation that when a mismatch occurs, the potential match between the substring and the text can be reused by starting the comparison from the next character in the text, rather than starting over from the beginning of the substring.
Here is an example of the KMP algorithm implemented in C:
Copy code
#include <stdio.h>
#include <string.h>
void computeLPS(char* pattern, int* lps) {
int m = strlen(pattern);
int len = 0;
lps[0] = 0;
int i = 1;
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
int search(char* text, char* pattern) {
int n = strlen(text);
int m = strlen(pattern);
int lps[m];
computeLPS(pattern, lps);
int i = 0;
int j = 0;
while (i < n) {
if (pattern[j] == text[i]) {
i++;
j++;
}
if (j == m) {
return i - j;
} else if (i < n && pattern[j] != text[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return -1;
}
int main() {
char text[] = "Hello, world!";
char pattern[]
Comments: 0