c语言代码写串的模式匹配
时间: 2023-09-27 07:08:31 浏览: 62
串的模式匹配是指在一个文本串中查找是否存在一个模式串,并返回该模式串在文本串中的起始位置。
以下是一个简单的C语言代码实现:
```c
#include <stdio.h>
#include <string.h>
int match(char *text, char *pattern) {
int i, j, k;
int n = strlen(text);
int m = strlen(pattern);
for (i = 0; i <= n - m; i++) {
k = i;
for (j = 0; j < m && pattern[j] == text[k]; j++, k++);
if (j == m) return i; // 匹配成功,返回起始位置
}
return -1; // 匹配失败
}
int main() {
char text[] = "hello world!";
char pattern[] = "world";
int pos = match(text, pattern);
if (pos != -1) {
printf("Matched at position %d\n", pos);
} else {
printf("Not found\n");
}
return 0;
}
```
在上面的代码中,`match` 函数实现了串的模式匹配。它使用了两个指针 `i` 和 `j` 分别指向文本串和模式串的当前位置。在每一次循环中,它比较当前位置的字符是否相同,如果相同则继续往后比较,否则退出循环。如果模式串中的所有字符都匹配成功,则返回起始位置,否则返回 -1 表示匹配失败。
在 `main` 函数中,我们调用了 `match` 函数并打印了匹配结果。在这个例子中,模式串 "world" 匹配了文本串 "hello world!" 中的 "world" 子串,因此输出 "Matched at position 6"。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)