Matching a pattern in a string involves searching for a specific sequence of characters within a larger string. In this article, we will learn different methods to efficiently match patterns in a string in C.
The most straightforward method to match a string is by using strstr() function. Let’s take a look at an example:
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "hello geeks";
char p[] = "geeks";
// Using strstr to find first occurrence
// of the pattern p in s
char *res = strstr(s, p);
if (res != NULL)
printf("Found at position: %ld", res - s);
else
printf("Not found.");
return 0;
}
Output
Found at position: 6
Explanation: The strstr() function in C is used to find the first occurrence of a substring (pattern) within a larger string. It returns a pointer to the first occurrence of the pattern in the string, or NULL if the pattern is not found. The function performs a case-sensitive search, meaning it will only match the exact characters as specified in the pattern.
There are also a few other methods to match a pattern in a string in C. Some of them are as follows:
Using Regular Expressions
We can use the regcomp() function to compile a regular expression pattern and regexec() to search for it in the given string. If the pattern matches the string, the function returns 1, otherwise, it returns 0.
#include <stdio.h>
#include <string.h>
#include <regex.h>
int search(char *s, char *p) {
regex_t regex;
int ret;
// Compile the regular expression
ret = regcomp(®ex, p, 0);
// Execute the regular expression match
ret = regexec(®ex, s, 0, NULL, 0);
regfree(®ex);
// Return 1 if match found, 0 otherwise
return ret == 0;
}
int main() {
char s[] = "hello geeks";
char p[] = "geeks";
// Matching pattern p in string s
int res = search(s, p);
if (res)
printf("Found");
else
printf("Not found.");
return 0;
}
Output
Found
Using a Loop
In this method, we iterate through the string and compare each character in the string with the pattern. If we find a match, we return the position of the match.
#include <stdio.h>
int search(char *s, char *p) {
int i = 0, j = 0;
// Traverse the string s
while (s[i] != '\0') {
// Match the characters of p one by one
if (s[i] == p[j]) {
j++;
// If all characters are matched
if (p[j] == '\0') return 1;
} else j = 0;
i++;
}
// If pattern is not found
return 0;
}
int main() {
char s[] = "hello geeks";
char p[] = "geeks";
// Matching pattern p in string s
int res = search(s, p);
if (res)
printf("Found");
else
printf("Not found.");
return 0;
}
Output
Found