用C语言编写函数统计一个英文句子中单词的个数在主函数中输入字符串调用此函数并输出结果
时间: 2024-04-29 21:23:33 浏览: 22
```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 <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函数来统计数字字符的个数,并将结果输出。
通过函数统计字符串中数字字符的个数,返回结果。在主函数中输入一串字符,调用函数输出结果,c语言
以下是统计字符串中数字字符个数的函数实现:
```c
#include <stdio.h>
int count_digits(char *str) {
int count = 0;
while (*str != '\0') {
if (*str >= '0' && *str <= '9') {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int count = count_digits(str);
printf("数字字符的个数为:%d\n", count);
return 0;
}
```
该程序首先定义了一个函数`count_digits`,该函数接受一个字符串参数`str`,并通过一个循环遍历字符串中的每个字符,判断是否为数字字符。如果是数字字符,则将计数器`count`加1。最后返回计数器的值。
在主函数中,首先提示用户输入一个字符串,并通过`scanf`函数将其读入。然后调用`count_digits`函数统计字符串中数字字符的个数,并将结果输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](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)