首页 > 编程语言 > 详细

C语言查找子字符串并计数

时间:2021-05-25 12:13:45      阅读:20      评论:0      收藏:0      [点我收藏+]
请编写一个查找子字符串的程序,并统计子字符串出现的次数。
**输入格式要求:"%s" 提示信息:"请输入主串:" "请输入要查找的串:"
**输出格式要求:"%s,%s:" "子串出现的次数:%d\n" "子串不在主串中\n"
程序运行示例1如下:
请输入主串:Hello,world!
请输入要查找的串:l
Hello,world!,l:子串出现的次数:3
程序运行示例2如下: 
请输入主串:Hello,world!
请输入要查找的串:abc
Hello,world!,abc:子串不在主串中
 
 1 #include<stdio.h>
 2 #include<string.h>
 3 #define N 80
 4 main()
 5 {
 6     char str1[N], str2[N];
 7     int count = 0, i, j, temp, k = 0;
 8     printf("请输入主串:");
 9     scanf("%s", str1);
10     printf("请输入要查找的串:");
11     scanf("%s", str2);
12     for (i = 0; i < strlen(str1) ;  i++)
13     {    
14         if (str1[i]==str2[0])
15         {
16             temp = i;
17             for (j = 0; j < strlen(str2); i++, j++)
18             {
19                 if (str1[i]!=str2[j])
20                     break;
21                 else
22                     k += 1;
23             }
24             if (k == strlen(str2))
25                 count += 1;
26                 k = 0;
27             i = temp;
28         }
29     }
30     printf("%s,%s:", str1, str2);
31     if (count == 0)
32         printf("子串不在主串中\n");
33     else
34         printf("子串出现的次数:%d\n", count);
35 }

 

C语言查找子字符串并计数

原文:https://www.cnblogs.com/20201212ycy/p/14807255.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!