搜索字符串中的子字符串及其位置

Searching a substring in a string and its position

我正在尝试编写一个代码来检查输入的子字符串是否在输入的字符串中。通过一些谷歌搜索,我设法做到了。但是我应该写一个代码来判断子字符串是否重复了几次。

例如,如果字符串是 "ABBABBABAAABBBABABAA",子字符串是 "BABA",则输出应该在 5-8、13-16、15-18 之间。

如何改进我的代码?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){

  char sntnc[400], word[400], *ptr; 
  puts("Please enter a string: ");
  gets(sntnc);
  puts("\nEnter a substring to be searched: ");
  gets(word);
  ptr=strstr(sntnc,word);
  if (strstr(sntnc, word)==NULL)
    printf("\nThe string doesn't contains the substring.");
  else 
    printf("\nPositin of the substring in the string: %d.", ptr - sntnc + 1);
  return 0;
}

找到子字符串的实例并打印其位置后,递增 ptr 使其指向下一个字符,然后再次调用 strstr 并使用 ptr 作为字符串搜索。循环直到 returns NULL:

ptr=strstr(sntnc,word);
if (strstr(sntnc, word)==NULL) {
   printf("\nThe string doesn't contains the substring.");
} else {
    do {
       printf("\nPositin of the substring in the string: %d.", ptr - sntnc + 1);
       ptr=strstr(ptr+1,word);
    while (ptr);
}

此外,gets 函数不安全。由于它不对输入执行边界检查,因此它可能允许写入超过目标缓冲区的末尾,从而调用未定义的行为。请改用 fgets