#include 'stdio.h' int Count_String(char a[],char b[]) { char *p1, *p2; int count = 0; gets(a); gets(b); p1 = a; p2 = b; while (*p1 == *p2) { if (*p1 == *p2) { while (*p1 == *p2 && *p2 != '\0') { p1++; p2++; } } else p1++; if (*p2 == '\0') count++; p2 = b; } return count; } int main(){ char a[32]; char b[32]; int res = Count_String(a,b); printf('%d',res); } 这段代码有几个问题:

  1. gets()函数已经被弃用,应该使用fgets()函数代替。

  2. Count_String()函数没有初始化输入的两个字符串数组,导致结果不确定。

  3. Count_String()函数中在字符串匹配成功时没有更新p1和p2的位置,导致会陷入死循环。

下面是修改后的代码:

#include 'stdio.h' #include 'string.h'

int Count_String(char a[], char b[]) { char *p1, *p2; int count = 0; fgets(a, 32, stdin); fgets(b, 32, stdin); p1 = a; p2 = b; while (*p1 != '\0' && *p2 != '\0') { if (*p1 == *p2) { p1++; p2++; } else { p1 = p1 - (p2 - b) + 1; p2 = b; } if (*p2 == '\0') { count++; p2 = b; } } return count; }

int main() { char a[32] = {0}; char b[32] = {0}; int res = Count_String(a, b); printf('%d', res); return 0; }

C语言字符串匹配代码错误分析及修正

原文地址: https://www.cveoy.top/t/topic/nqI5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录