【问题标题】:C- pattern matchingC-模式匹配
【发布时间】:2017-10-21 18:57:48
【问题描述】:

我正在尝试编写一个无限接收输入的程序,每当输入序列与给定模式匹配时,它应该打印已找到匹配项并继续搜索我设法编写的其他模式的出现

   #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;
    }

问题是这段代码不能处理像 11234 这样的重复情况。

我的其他方法使用缓冲,有一些错误

#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;
}

帮我解决问题

【问题讨论】:

标签: c pattern-matching


【解决方案1】:

问题是当一个给定的字符,比如输入的第二个1,不满足if(ch==pattern[i])-条件时,你“重置”了模式,但你不会检查这个已经输入的1 “新”模式检查的开始。所以写如下:

else {
   i = (ch==pattern[0]) ? 1 : 0;

【讨论】:

  • 如果要找到的模式是1213 并且输入是121213,这可能会遇到问题。明明有匹配,但是当第二个 2 匹配 3 失败时,重置回模式的开头意味着错过了 1213。
猜你喜欢
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2020-12-04
  • 2011-09-08
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多