C语言如何统计某字符串在一串字符中出现的次数
时间: 2023-11-14 10:06:14 浏览: 39
可以使用循环遍历字符串的每个字符,将每个字符与目标字符串的第一个字符进行比较,如果相同,则继续比较下一个字符,直到目标字符串的所有字符都比较完毕。如果比较过程中出现不同的字符,则跳出当前循环,继续比较下一个字符。如果目标字符串的所有字符都比较完毕,且每个字符都与字符串中的对应字符相同,则说明目标字符串在该字符串中出现了一次,计数器加一。最后循环结束后,计数器的值即为目标字符串在该字符串中出现的次数。
下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
int count_occurrences(char *str, char *target) {
int count = 0;
int n = strlen(target);
while (*str) {
if (strncmp(str, target, n) == 0) {
count++;
str += n;
} else {
str++;
}
}
return count;
}
int main() {
char str[] = "hello world, hello";
char target[] = "hello";
int count = count_occurrences(str, target);
printf("The string '%s' appears %d times in '%s'\n", target, count, str);
return 0;
}
```
输出:
```
The string 'hello' appears 2 times in 'hello world, hello'
```