用c语言循环统计子字符串substr在字符串str中出现的次数
时间: 2023-11-17 18:06:14 浏览: 84
可以使用两层循环遍历字符串str,逐个匹配判断是否为子字符串substr,并在匹配成功时计数器加1。具体代码如下:
```c
#include <stdio.h>
#include <string.h>
int count_substr(const char* str, const char* substr) {
int count = 0;
int len_str = strlen(str);
int len_substr = strlen(substr);
for (int i = 0; i < len_str - len_substr + 1; i++) { // 遍历字符串str
int j;
for (j = 0; j < len_substr; j++) { // 遍历子字符串substr
if (str[i+j] != substr[j])
break;
}
if (j == len_substr) // 匹配成功
count++;
}
return count;
}
int main() {
char str[] = "hello world, hello everyone!";
char substr[] = "hello";
int count = count_substr(str, substr);
printf("'%s' appears %d times in '%s'\n", substr, count, str);
return 0;
}
```
输出:
```
'hello' appears 2 times in 'hello world, hello everyone!'
```
阅读全文