C语言程序,统计字符串s在字符串str中出现的次数
时间: 2023-11-14 18:06:14 浏览: 60
您好,我可以回答您的问题。以下是实现统计字符串s在字符串str中出现的次数的C语言代码:
```
#include <stdio.h>
#include <string.h>
int count(char *str, char *s) {
int len_str = strlen(str);
int len_s = strlen(s);
int cnt = 0;
for (int i = 0; i <= len_str - len_s; i++) {
int j = 0;
while (j < len_s && s[j] == str[i+j]) {
j++;
}
if (j == len_s) {
cnt++;
}
}
return cnt;
}
int main() {
char str[100];
char s[20];
printf("请输入字符串str:\n");
scanf("%s", str);
printf("请输入字符串s:\n");
scanf("%s", s);
int cnt = count(str, s);
printf("%s在%s中出现的次数为:%d\n", s, str, cnt);
return 0;
}
```
如果您需要进一步了解代码的细节,可以参考注释。
相关问题
c语言,统计字符串s在字符串str中出现的次数。
可以使用字符串匹配的方法来统计字符串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'
```
C语言编写程序,统计字符串s在字符串str中出现的次数
下面是C语言代码实现,可以统计字符串s在字符串str中出现的次数:
```c
#include <stdio.h>
#include <string.h>
int countSubstring(char str[], char s[]) {
int count = 0, i, j, len, len2;
len = strlen(str);
len2 = strlen(s);
for(i = 0; i <= len - len2; i++) {
for(j = 0; j < len2; j++) {
if(str[i+j] != s[j])
break;
}
if(j == len2)
count++;
}
return count;
}
int main() {
char str[100], s[100];
int count;
printf("Enter a string: ");
gets(str);
printf("Enter a substring: ");
gets(s);
count = countSubstring(str, s);
printf("The substring '%s' appears %d times in '%s'\n", s, count, str);
return 0;
}
```
在这个代码中,我们定义了一个函数`countSubstring`,它接收两个参数,分别是字符串`str`和字符串`s`。这个函数的作用是统计字符串`s`在字符串`str`中出现的次数。具体实现是,我们通过两个嵌套的循环来遍历字符串`str`,在每个位置上判断是否出现了字符串`s`,如果出现了,就累加计数器`count`。最后将计数器的值返回即可。
在主函数中,我们通过`gets`函数从标准输入中读入字符串`str`和字符串`s`,然后调用`countSubstring`函数计算出现次数,并输出结果。