程序7.题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

本程序通过while循环遍历输入的字符串,使用if语句判断并计数字符串中英文字母、空格、数字和其他字符的个数,最后输出各个类别字符的数量。
 

/*【程序7】
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
1.程序分析:利用while语句,条件为输入的字符不为'\n'.
*/

public class Pro7{
 public static void main(String[] args){
  String ss="asfkjh3  14&*……";
  /*for(String s:ss)
  {  
   System.out.print(s);
  }*/
  int x=0;
  int eng=0,spa=0,num=0,other=0;
  while(x<ss.length()){
   if(ss.charAt(x)<='z'&&ss.charAt(x)>='a')
   eng++;
   else if(ss.charAt(x)==' ')//要用else if
   spa++;
   else if(ss.charAt(x)<='9'&&ss.charAt(x)>='0')
   num++;
   else
   other++;
   x++;   
  }
   System.out.println("英文字母个数"+eng);
   System.out.println("空格数"+spa);
   System.out.println("数字数"+num);
   System.out.println("其他字符"+other);
 }
}

以下为几种使用C语言统计输入一行字符英文字母空格数字其它字符个数的代码实现: ### 实现方式一 使用`getchar`函数逐个读取字符并进行判断: ```c #include <stdio.h> void main() { char c; int letter = 0, number = 0, space = 0, other = 0; printf("请输入一行字符:\n"); while ((c = getchar()) != '\n') { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z' )) { letter++; } else if (c >= '0' && c <= '9') { number++; } else if (c == ' ') { space++; } else { other++; } } printf("字母%d个,数字%d个,空格%d个,其他%d个", letter, number, space, other); } ``` ### 实现方式二 使用`fgets`读取一行字符,并借助`ctype.h`头文件中的函数进行字符类型判断: ```c #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <ctype.h> int main() { char input[1000]; int letter_count = 0; int space_count = 0; int digit_count = 0; int other_count = 0; printf("请输入一行字符:"); fgets(input, sizeof(input), stdin); for (int i = 0; input[i] != '\0'; i++) { if (isalpha(input[i])) { letter_count++; } else if (isspace(input[i])) { space_count++; } else if (isdigit(input[i])) { digit_count++; } else { other_count++; } } printf("英文字母个数:%d\n", letter_count); printf("空格个数:%d\n", space_count); printf("数字个数:%d\n", digit_count); printf("其他字符个数:%d\n", other_count); return 0; } ``` ### 实现方式三 同样使用`getchar`函数逐个读取字符并判断: ```c #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char ch; int letter = 0,digital = 0,space = 0,other = 0; while((ch = getchar()) != '\n') { if( ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' ) letter++; else if(ch >= '0' && ch <= '9' ) digital++; else if(ch == ' ') space++; else other++; } printf("字母=%d,数字=%d,空格=%d,其它字符=%d\n",letter,digital,space,other); return 0; } ``` ### 实现方式四 使用`getchar`逐个读取字符并进行分类统计: ```c #include<stdio.h> int main() { char c; int letters=0,space=0,digit=0,other=0; printf("请输入一行字符:\n"); while((c=getchar())!='\n') { if(c>='a'&&c<='z'||c>='A'&&c<='Z') letters++; else if(c==' ') space++; else if(c>='0'&&c<='9') digit++; else other++; } printf("字母数:%d\n空格:%d\n数字:%d\n其他字符:%d\n",letters,space,digit,other); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值