If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, pattern searching is the process of finding a specific sequence of characters (known as the pattern) within a larger string (known as the text). There are various algorithms that can be used to perform pattern searching, with different trade-offs in terms of performance and complexity.
The most basic algorithm for pattern searching is the brute-force algorithm, also known as the naive algorithm. It compares each character of the text with the corresponding character of the pattern, and if a mismatch is found, it starts over from the next character in the text.
Here is an example of the brute-force algorithm implemented in C:
Copy code
#include <stdio.h>
int search(char* text, char* pattern) {
int n = strlen(text);
int m = strlen(pattern);
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (text[i + j] != pattern[j]) {
break;
}
}
if (j == m) {
return i;
}
}
return -1;
}
int main() {
char text[] = "Hello, world!";
char pattern[] = "world";
int index = search(text, pattern);
if (index == -1) {
printf("Pattern not found in text.\n");
} else {
printf("Pattern found at index %d.\n", index);
}
return 0;
}
In this example, the function search()
takes a text and a pattern as input and returns the starting index of the first occurrence of the pattern in the text. If the pattern is not found in the text, it returns -1.
However, the brute-
Comments: 0