编写函数统计字符串1在字符串2中出现的次数以及每次出现的位置,要求用字符指针作为函数参数

编写函数统计字符串1在字符串2中出现的次数以及每次出现的位置,要求用字符指针做为函数的参数。(例如:字符串1是“do”,字符串2是“Howdoyoudo?”)则统计结果为2次,第1次距离文本开头4个字符,第2次距离文本开头11个字符)

详细代码和注释如下,望采纳

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

// 定义函数,用于统计字符串1在字符串2中出现的次数以及每次出现的位置
void count_string(const char *str1, const char *str2) {
  int i, j, count = 0, len1 = strlen(str1), len2 = strlen(str2);

  // 遍历字符串2,查找字符串1
  for (i = 0; i < len2 - len1 + 1; i++) {
    // 如果找到字符串1的第一个字符
    if (str2[i] == str1[0]) {
      // 检查后面的字符是否也相同
      for (j = 1; j < len1; j++) {
        if (str2[i + j] != str1[j]) {
          break;
        }
      }

      // 如果找到了字符串1
      if (j == len1) {
        // 统计出现次数和出现位置
        count++;
        printf("第%d次距离文本开头%d个字符\n", count, i);
      }
    }
  }

  // 输出结果
  printf("字符串1在字符串2中出现的次数:%d\n", count);
}