C语言字符串匹配算法:通配符'*'和'?'的实现
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// 判断两个字符串是否匹配
bool isMatch(char* str1, char* str2) {
// 边界情况,如果两个字符串同时为空,则匹配成功
if (*str1 == '\0' && *str2 == '\0') {
return true;
}
// 如果第一个字符串为空,第二个字符串必须全为'*'才能匹配
if (*str1 == '\0') {
while (*str2 == '*') {
str2++;
}
return *str2 == '\0';
}
// 如果第二个字符串为空,第一个字符串不为空,无法匹配
if (*str2 == '\0') {
return false;
}
// 如果两个字符串的当前字符匹配,或者第二个字符串的当前字符为'?',则继续匹配下一个字符
if (*str1 == *str2 || *str2 == '?') {
return isMatch(str1 + 1, str2 + 1);
}
// 如果第二个字符串的当前字符为'*',则可以选择匹配0个字符或者多个字符
if (*str2 == '*') {
return isMatch(str1, str2 + 1) || isMatch(str1 + 1, str2);
}
// 其他情况下,无法匹配
return false;
}
int main() {
char str1[100];
char str2[100];
printf("请输入第一个字符串:");
fgets(str1, sizeof(str1), stdin);
printf("请输入第二个字符串:");
fgets(str2, sizeof(str2), stdin);
// 去除字符串中的换行符
str1[strcspn(str1, "\n")] = '\0';
str2[strcspn(str2, "\n")] = '\0';
bool match = isMatch(str1, str2);
if (match) {
printf("yes\n");
} else {
printf("no\n");
}
return 0;
}
使用C语言编写的程序,通过递归的方式判断两个字符串是否匹配。根据两个字符串的当前字符进行不同的处理,如果当前字符匹配或者第二个字符串的当前字符为'?',则继续匹配下一个字符;如果第二个字符串的当前字符为'*',则可以选择匹配0个字符或者多个字符;其他情况下,无法匹配。根据匹配结果输出对应的结果。
原文地址: https://www.cveoy.top/t/topic/bEPf 著作权归作者所有。请勿转载和采集!