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

mac2026-01-27  3

 

import java.util.Scanner; class Test07 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入字符串:"); String str = sc.nextLine(); //toCharArray()方法将字符串转换为字符数组 char[] chs = str.toCharArray(); int englishNum = 0; int spaceNum = 0; int numberNum = 0; int otherNum = 0; for(int i=0;i<chs.length;i++){ if((chs[i]>='A'&&chs[i]<='Z')||(chs[i]>='a'&&chs[i]<='z')){ englishNum++; }else if(chs[i]==' '){ spaceNum++; }else if(chs[i]>='0'&&chs[i]<='9'){ numberNum++; }else{ otherNum++; } } System.out.println("englishNum="+englishNum+",spaceNum="+spaceNum+",numberNum="+numberNum+",otherNum="+otherNum); } }

输出结果】

最新回复(0)