今日学习任务
|
|
今日任务完成情况 |
|
今日开发中出现的问题汇总
|
|
今日未解决问题 | 无 |
今日开发收获 |
|
自我评价 |
|
其他
| 无 |
1、输入一个字符串,计算字符串中子串出现的次数。
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #define MAX_LEN sizeof(char)*50
6
7 int count_str()
8 {
9 int i;
10 int n;
11 int count = 0;
12
13 char *ptr = (char *)malloc(MAX_LEN);
14 char *str = (char *)malloc(MAX_LEN);
15 char *p_temp = ptr;
16 char *s_temp = str;
17
18 if(ptr == NULL || str == NULL)
19 {
20 printf("malloc error\n");
21 exit(1);
22 }
23
24 memset(ptr,0,MAX_LEN);
25 memset(str,0,MAX_LEN);
26
27 printf("Please input string:\n");
28 scanf("%s",ptr);
29 printf("Please input substring:\n");
30 scanf("%s",str);
31
32 n = strlen(str);
33
34 while(*p_temp != 0)
35 {
36 if(strncmp(p_temp, s_temp, n) == 0)
37 {
38 count ++;
39 p_temp = p_temp + n;
40 }
41 p_temp ++;
42 }
43
44 free(ptr);
45 free(str);
46
47 ptr = NULL;
48 str = NULL;
49
50 return count;
51 }
52
53 int main()
54 {
55 int result;
56
57 result = count_str();
58
59 printf("result = %d\n",result);
60
61 return 0;
62 }
运行结果:
Please input string:
123jkkasjdffiaweowo3123jka123klafjk123
Please input substring:
123
result = 4