首页 > 解决方案 > 当没有子字符串时,K&R 的几乎相似的 strindex 实现找到了子字符串

问题描述

我试图实现 K&R strindex 程序。将要求用户输入一行,如果该行包含字符串“boi”,程序将确认该行包含该模式。问题是,程序确认其他一些字符串/字符串。

如果我输入“şgb”,它将确认它包含字符串“boi”。到目前为止,它只发生在“şgb”上。

https://onlinegdb.com/SyeeO0mzH


#include <stdio.h>

#define MAXLINE_LENGTH 100

char pattern[] = "boi";

int get_line(char line[], int maxlength);
int str_index(char str[], char substr[]);

int main() {
  char line[MAXLINE_LENGTH];

  while(get_line(line, MAXLINE_LENGTH) > 0) {
    if(str_index(line, pattern) >= 0) {
      printf("%s", line);
      printf("Pattern found above line\n");
    }
  }

  return 0;
}

int get_line(char line[], int maxlength){
  int index = 0, character;

  while(--maxlength > 0 && (character = getchar()) != EOF && character != '\n') {
    line[index++] = character;
  }

  if(character == '\n') {
    line[index++] = character;
  }

  line[index] = '\0';

  return index;
}

int str_index(char str[], char substr[]) {
  int i, j, k;

  for(i = 0; str[i] != '\0'; i++) {
    for(j = i, k = 0; substr[k] != '\0' && str[j] == substr[k]; j++, k++) ;

    if(k > 0) {
      return i;
    }
  }

  return -1;
}

boi
boi
Pattern found above line
fbajdobadşgbadf
fbajdobadşgbadf
Pattern found above line
şgb
şgb
Pattern found above line

标签: c

解决方案



推荐阅读