鱼C论坛

 找回密码
 立即注册
查看: 2207|回复: 1

[已解决]统计一个字符串在另一个字符串中出现的次数

[复制链接]
发表于 2021-1-2 14:34:44 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
编写一个函数,该函数可以统计一个长度为3的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为:asdasasdfgasdaszx67asdmklo,字符串为:asd,则应输出n=4。
最佳答案
2021-1-2 14:42:43
  1. // 编写一个函数,该函数可以统计一个长度为3的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为:asdasasdfgasdaszx67asdmklo,字符串为:asd,则应输出n=4。
  2. #include <stdio.h>
  3. #include <string.h>

  4. int fun(char *str, char *substr);
  5. int main(void)
  6. {
  7.     char str[81] = "asdasasdfgasdaszx67asdmklo", substr[4] = "asd";
  8.     int n;
  9.     n = fun(str, substr);
  10.     printf("n=%d\n", n);
  11.     return 0;
  12. }


  13. int fun(char *str, char *substr)
  14. {
  15.     int ret = 0;
  16.     char temp[4] = { 0 };

  17.     for (int i = 0; str[i] != '\0';i++)
  18.     {
  19.         strncpy(temp, str+i, 3); //每次取3个字符给temp,再与substr比较

  20.         if (strcmp(temp, substr) == 0)
  21.             ret++;
  22.     }
  23.     return ret;
  24. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-1-2 14:42:43 | 显示全部楼层    本楼为最佳答案   
  1. // 编写一个函数,该函数可以统计一个长度为3的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为:asdasasdfgasdaszx67asdmklo,字符串为:asd,则应输出n=4。
  2. #include <stdio.h>
  3. #include <string.h>

  4. int fun(char *str, char *substr);
  5. int main(void)
  6. {
  7.     char str[81] = "asdasasdfgasdaszx67asdmklo", substr[4] = "asd";
  8.     int n;
  9.     n = fun(str, substr);
  10.     printf("n=%d\n", n);
  11.     return 0;
  12. }


  13. int fun(char *str, char *substr)
  14. {
  15.     int ret = 0;
  16.     char temp[4] = { 0 };

  17.     for (int i = 0; str[i] != '\0';i++)
  18.     {
  19.         strncpy(temp, str+i, 3); //每次取3个字符给temp,再与substr比较

  20.         if (strcmp(temp, substr) == 0)
  21.             ret++;
  22.     }
  23.     return ret;
  24. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-3 17:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表