用c语言写出统计字符串s在字符串str中出现的次数的代码
时间: 2023-11-15 16:06:39 浏览: 35
好的,以下是用C语言编写统计字符串s在字符串str中出现次数的代码:
```c
#include <stdio.h>
#include <string.h>
int count_substr(const char *str, const char *s) {
int count = 0, len = strlen(s);
while (*str != '\0') {
if (strncmp(str, s, len) == 0) {
count++;
}
str++;
}
return count;
}
int main() {
char str[] = "The quick brown fox jumps over the lazy dog";
char s[] = "the";
int count = count_substr(str, s);
printf("%s appears %d times in %s\n", s, count, str);
return 0;
}
```
解释:该代码利用了循环逐个扫描字符串 `str` 中的每个子串,并在扫描时使用 `strncmp` 函数比对与目标子串 `s` 是否相等,若相等则自增统计变量 `count`。最后输出结果即可。
相关问题
用c语言写出统计一个字符串中的字母,数字、空格和其他字符的个数
你好,这个问题可以回答。以下是用 C 语言实现统计字符串中字母、数字、空格和其他字符个数的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isdigit(str[i])) {
digits++;
} else if (isspace(str[i])) {
spaces++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
希望能对你有所帮助。
使用c语言写出一个字符串统计的程序,统计要统计字符串中数字、小写字母、大写字母每种各有多少个
下面是使用C语言编写的字符串统计程序:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, digits = 0, lowercase = 0, uppercase = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
for(i = 0; str[i] != '\0'; i++) {
if(isdigit(str[i])) {
digits++;
} else if(islower(str[i])) {
lowercase++;
} else if(isupper(str[i])) {
uppercase++;
}
}
printf("数字个数:%d\n", digits);
printf("小写字母个数:%d\n", lowercase);
printf("大写字母个数:%d\n", uppercase);
return 0;
}
```
程序中定义了一个字符数组 `str`,用于存储用户输入的字符串。接着,使用 `fgets()` 函数从标准输入读取用户输入的字符串,并使用 `for` 循环遍历字符串中的每一个字符,判断其是否为数字、小写字母或大写字母,并分别统计它们的数量。最后,打印出统计结果。