任意输入一串字符保存在字符数组中,求期中字母,数字及其他字符的个数。空格算其他字符。例如: chars[100];gets(s);比如输入了:my age is 28 结果显示为:字母7个,数字2个,其他3个。
时间: 2024-02-09 18:13:23 浏览: 23
好的,可以用以下代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char chars[100];
int letter_count = 0, digit_count = 0, other_count = 0;
printf("请输入一串字符:");
gets(chars);
for (int i = 0; chars[i] != '\0'; i++) {
if (isalpha(chars[i])) {
letter_count++;
} else if (isdigit(chars[i])) {
digit_count++;
} else {
other_count++;
}
}
printf("字母%d个,数字%d个,其他%d个。\n", letter_count, digit_count, other_count);
return 0;
}
```
该程序使用了 `isalpha` 和 `isdigit` 函数来判断每个字符是字母还是数字,以及 `other_count` 统计其他字符的数量。注意,该程序使用了不安全的 `gets` 函数,实际上应该使用 `fgets` 函数来更安全地读取用户输入。
相关问题
java输入一串字符,统计其中数字、字母空格及其他字符的个数
可以使用Java的字符数组和循环语句来实现统计不同字符类型个数的功能。例如:
```java
import java.util.Scanner;
public class CharCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一串字符:");
String input = scanner.nextLine();
int letterCount = 0;
int digitCount = 0;
int spaceCount = 0;
int otherCount = 0;
char[] chars = input.toCharArray(); // 将字符串转换为字符数组
for (char c : chars) {
if (Character.isLetter(c)) { // 判断是否为字母
letterCount++;
} else if (Character.isDigit(c)) { // 判断是否为数字
digitCount++;
} else if (Character.isSpaceChar(c)) { // 判断是否为空格
spaceCount++;
} else { // 其他字符
otherCount++;
}
}
System.out.println("字母个数:" + letterCount);
System.out.println("数字个数:" + digitCount);
System.out.println("空格个数:" + spaceCount);
System.out.println("其他字符个数:" + otherCount);
}
}
```
运行结果示例:
```
请输入一串字符:
Hello World! 123
字母个数:10
数字个数:3
空格个数:2
其他字符个数:1
```
在c语言中统计一个字符串中字母,空格,数字和其他字符的个数,主函数负责输入和输出。
好的,这里是一个示例代码,可以实现你所需的功能:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *letters, int *spaces, int *digits, int *others) {
while(*str) {
if(isalpha(*str)) {
(*letters)++;
} else if(isspace(*str)) {
(*spaces)++;
} else if(isdigit(*str)) {
(*digits)++;
} else {
(*others)++;
}
str++;
}
}
int main() {
char str[100];
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入一个字符串:\n");
fgets(str, 100, stdin);
count_chars(str, &letters, &spaces, &digits, &others);
printf("字母个数:%d\n", letters);
printf("空格个数:%d\n", spaces);
printf("数字个数:%d\n", digits);
printf("其他字符个数:%d\n", others);
return 0;
}
```
在这个程序中,`count_chars()` 函数用于统计一个字符串中字母,空格,数字和其他字符的个数。`main()` 函数负责输入和输出。当你输入一个字符串时,程序将会输出该字符串中字母,空格,数字和其他字符的个数。
希望对你有帮助!