EOJ-319-字符串出现次数

定义函数 count(s,t),计算 t 在 s 中出现的次数。输入数据保证如有多个 t 的话,这些 t 不会相互重叠。

提示

例如:ababcdabcd 中出现 2 次,aaxyaabb 中出现 1 次,xyx 中出现 0 次。
只需按要求写出函数定义,并使用给定的测试程序测试你所定义函数的正确性。
不要改动测试程序。
测试正确后,将测试程序和函数定义一起提交到考试系统。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/***************************************************************/
/* */
/* DON'T MODIFY main function ANYWAY! */
/* */
/***************************************************************/
#include <stdio.h>
int count(char s[],char t[])
/* precondition: s 和 t 是两个字符串,t 不会是空串,且 t 不会重叠
postcondition: 返回 t 在 s 中出现的次数
*/
{ //TODO: your function definition
}
/***************************************************************/

#define N 80

int main()
{ char s[N+1],t[N+1];
scanf("%s%s",s,t);
//********** count is called here ******************
printf("%d\n",count(s,t));
//**************************************************
return 0;
}

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <cstring>
using namespace std;
int count(char s[],char t[])
/* precondition: s 和 t 是两个字符串,t 不会是空串,且 t 不会重叠
postcondition: 返回 t 在 s 中出现的次数
*/
{ //TODO: your function definition
int cnt = 0, s_len = strlen(s), t_len = strlen(t);
int i, j;
for (i = 0,j=0;i < s_len;i++) {
if (s[i] == t[j]) {
if (j== t_len-1) {
cnt++;
j = 0;
continue;
}
j++;
}else
j = 0;
}
return cnt;
}
/***************************************************************/

#define N 80

int main()
{ char s[N+1],t[N+1];
scanf("%s%s",s,t);
//********** count is called here ******************
printf("%d\n",count(s,t));
//**************************************************
return 0;
}

----\(˙<>˙)/----赞赏一下吧~