用C语言编写函数统计一个英文句子中单词的个数在主函数中输入字符串调用此函数并输出结果
时间: 2024-04-29 10:23:33 浏览: 138
```c
#include<stdio.h>
#include<string.h>
int countWords(char str[]) {
int count = 0;
int len = strlen(str);
int i;
for(i = 0; i < len; i++) {
if(str[i] == ' ' || str[i] == '\t' || str[i] == '\n') {
count++;
}
}
return count + 1;
}
int main() {
char str[100];
printf("输入一个英文句子:\n");
fgets(str, 100, stdin);
int count = countWords(str);
printf("单词的个数为:%d\n", count);
return 0;
}
```
输出:
```
输入一个英文句子:
The quick brown fox jumps over the lazy dog.
单词的个数为:9
```
相关问题
用c语言编写一个函数,由实参传来一个字符串,统计此字符串中字母、空格、数字和其他字符的个数;在主函数中输入字符串,然后调用该函数进行统计并(在主函数中)输出结果
下面是实现该功能的 C 代码:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *alpha, int *space, int *digit, int *other)
{
int i = 0;
char ch;
while ((ch = str[i]) != '\0') {
if (isalpha(ch)) {
(*alpha)++;
} else if (isspace(ch)) {
(*space)++;
} else if (isdigit(ch)) {
(*digit)++;
} else {
(*other)++;
}
i++;
}
}
int main(void)
{
char str[100];
int alpha = 0, space = 0, digit = 0, other = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
count_chars(str, &alpha, &space, &digit, &other);
printf("Number of alphabetic characters: %d\n", alpha);
printf("Number of spaces: %d\n", space);
printf("Number of digits: %d\n", digit);
printf("Number of other characters: %d\n", other);
return 0;
}
```
在 `count_chars` 函数中,我们遍历字符串中的每个字符,使用 `isalpha`、`isspace` 和 `isdigit` 函数判断该字符属于哪一类,并将相应的计数器加一。
在 `main` 函数中,我们首先通过 `fgets` 函数从标准输入中读取一个字符串,然后调用 `count_chars` 函数统计该字符串中的各种字符的个数,并输出结果。
用C语言编写函数,求给定字符串中数字字符的个数,在主函数中输入字符串及输出统计的个数。
以下用C语言编写函数,求给定字符串中数字字符的个数的示例代码:
```c
#include <stdio.h>
#include <string.h>
int countDigits(char str[]) {
int count = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
return count;
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
int count = countDigits(str);
printf("数字字符的个数为:%d\n", count);
return 0;
}
```
该程序中,countDigits函数用于统计给定字符串中数字字符的个数。它接受一个字符串参数str,并返回一个整数结果count。
函数中使用了一个for循环来遍历整个字符串,对于每个字符,如果它是一个数字字符(即ASCII码值在'0'~'9'之间),则将计数器count加1。
在主函数中,首先提示用户输入字符串,然后调用countDigits函数来统计数字字符的个数,并将结果输出。
阅读全文
相关推荐














