用c语言编写在一行中输入长度不超过40的字符串,分别统计一个字符串中出现小写字母、大写字母、数字和空格的个数。
时间: 2024-06-14 21:03:19 浏览: 15
以下是用C语言编写的统计字符串中小写字母、大写字母、数字和空格个数的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[41];
int i, upper = 0, lower = 0, digit = 0, space = 0;
printf("请输入一个长度不超过40的字符串:");
fgets(str, 41, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
upper++;
} else if (islower(str[i])) {
lower++;
} else if (isdigit(str[i])) {
digit++;
} else if (isspace(str[i])) {
space++;
}
}
printf("大写字母个数:%d\n", upper);
printf("小写字母个数:%d\n", lower);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
return 0;
}
```
相关问题
在c语言中实现:输入一个长度不超过20的字符串,将字符串中的所有小写字母替换为大写字母
以下是在C语言中实现将字符串中的小写字母替换为大写字母的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[21]; //定义一个长度为21的字符数组,用于存储输入的字符串
int i;
printf("请输入一个长度不超过20的字符串:");
scanf("%s", str); //输入字符串
for (i = 0; i < strlen(str); i++) { //遍历字符串中的每一个字符
if (str[i] >= 'a' && str[i] <= 'z') { //如果该字符是小写字母
str[i] = str[i] - 32; //将小写字母转换为大写字母
}
}
printf("转换后的字符串为:%s", str); //输出转换后的字符串
return 0;
}
```
在上述代码中,我们定义了一个长度为21的字符数组用于存储输入的字符串。然后使用scanf函数输入字符串。接着使用for循环遍历字符串中的每一个字符,如果该字符是小写字母,则通过ASCII码将其转换为大写字母。最后使用printf函数输出转换后的字符串。
用c语言编写一个程序,在程序中输入字符串,统计其中大写字母、小写字母和数字字符的个数
好的,下面是用 C 语言编写的程序,可以统计输入字符串中大写字母、小写字母和数字字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
int main(void) {
char str[100];
int upper = 0, lower = 0, digit = 0;
// 读取字符串
printf("请输入一个字符串:");
fgets(str, 100, stdin);
// 统计字符数量
for (int i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
upper++;
} else if (islower(str[i])) {
lower++;
} else if (isdigit(str[i])) {
digit++;
}
}
// 输出结果
printf("大写字母个数:%d\n", upper);
printf("小写字母个数:%d\n", lower);
printf("数字字符个数:%d\n", digit);
return 0;
}
```
程序中先定义了三个变量 `upper`、`lower` 和 `digit` 分别用于统计大写字母、小写字母和数字字符的个数。然后使用 `fgets()` 函数读取用户输入的字符串,遍历字符串中的每个字符,并使用 `isupper()`、`islower()` 和 `isdigit()` 函数判断字符是否为大写字母、小写字母或数字字符,然后分别对应地增加相应的计数器。最后通过 `printf()` 函数输出统计结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)