c语言,统计字符串s在字符串str中出现的次数。
时间: 2023-06-12 11:03:50 浏览: 70
可以使用字符串匹配的方法来统计字符串s在字符串str中出现的次数。以下是一个基于C语言的例子:
```c
#include <stdio.h>
#include <string.h>
// 统计字符串s在字符串str中出现的次数
int countOccurrences(char *str, char *s)
{
int count = 0;
int len = strlen(s);
while (*str)
{
if (strncmp(str, s, len) == 0)
{
count++;
str += len; // 将指针移动到下一个可能的匹配位置
}
else
{
str++;
}
}
return count;
}
int main()
{
char str[] = "hello, world! hello, hello";
char s[] = "hello";
int count = countOccurrences(str, s);
printf("'%s' occurs %d times in '%s'\n", s, count, str);
return 0;
}
```
输出结果为:
```
'hello' occurs 3 times in 'hello, world! hello, hello'
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)