[英]C- pattern matching
I am trying to write a program that receives input infinitely and whenever an input sequence matches a given pattern it should print that a match has been found and continue searching for other occurrences of the pattern I managed just to code this 我正在尝试编写一个程序,该程序可以无限接收输入,并且只要输入序列与给定的模式匹配,它就应该打印出已找到匹配项,并继续搜索其他出现的模式,我设法将其编码
#include<stdio.h>
#include<string.h>
int main(){
char ch;
char pattern[4]="1234";
int i=0;
while(1){
scanf(" %c",&ch);
if(ch==pattern[i]){
i+=1;
} else {
i = 0;
}
if (i == 4) {
printf("match found!\n");
i = 0;
}
//printf("%c",ch);
}
return 0;
}
The problem is that this code doesn't handle repetion cases like 11234 . 问题在于该代码无法处理类似11234的重复情况。
my other approach uses buffering, that has some error 我的另一种方法使用缓冲,这有一些错误
#include<stdio.h>
#include<string.h>
int main(){
char ch;
char pattern[4]="1234";
char buf[4] = "";
int i=0;
while(1){
scanf(" %c",&ch);
buf[i%4]=ch;
i++;
if(strcmp(pattern,buf)==0){
printf("Match found");
}
}
return 0;
}
Help me fix the problem 帮我解决问题
The problem is that when a given character, let's say the second 1
entered, does not fulfill the if(ch==pattern[i])
-condition, you "reset" the pattern but you will not check this already entered 1
for the beginning of the "new" pattern check. 问题在于,当给定字符(假设输入的第二个1
不满足if(ch==pattern[i])
condition时,您可以“重置”模式,但不会检查已输入的1
“新”模式检查的开始。 So write the following: 因此,编写以下代码:
else {
i = (ch==pattern[0]) ? 1 : 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.