用C语言编写函数 统计子串sub在母串中的出现次数
时间: 2023-12-18 19:28:37 浏览: 156
以下是用C语言编写函数统计子串在母串中出现次数的示例代码:
```c
#include <stdio.h>
#include <string.h>
int countSubstring(char *str, char *sub) {
int count = 0;
int len1 = strlen(str);
int len2 = strlen(sub);
for (int i = 0; i <= len1 - len2; i++) {
int j;
for (j = 0; j < len2; j++) {
if (str[i + j] != sub[j]) {
break;
}
}
if (j == len2) {
count++;
}
}
return count;
}
int main() {
char str[] = "hello world, world is beautiful";
char sub[] = "world";
int count = countSubstring(str, sub);
printf("'%s' appears %d times in '%s'\n", sub, count, str);
return 0;
}
```
输出结果为:
```
'world' appears 2 times in 'hello world, world is beautiful'
```
阅读全文