判断键盘输入的字符串各个字符个数
package test; import java.util.*; public class test { public static int[] num(String sentence){ int[] res=new int[4]; for(int i=0;i<sentence.length();i++){ char ch=sentence.charAt(i); if(ch<='Z'&&ch>='A'||ch<='z'&&ch>='a') res[0]++; else if(ch==' ') res[1]++; else if('1'<=ch&&'9'>=ch) res[2]++; else res[3]++; } return res; } public static void main(String arg[]){ System.out.println("请输入一行内容,以回车符结尾"); Scanner scan=new Scanner(System.in); String sentence=scan.nextLine(); int[] result=num(sentence); System.out.print("该行包含的英文、空格、数字及其它字符的个数分别为:"); System.out.print(result[0]+""+result[1]+""+result[2]+""+result[3]); } }
或使用正则表达式判断
package test; import java.util.*; public class test { public static int[] num(String sentence){ int[] res=new int[4]; for(int i=0;i<sentence.length();i++){ char ch=sentence.charAt(i); if(String.valueOf(ch).matches("^[A-Za-z]+$"))//字母正则表达式 res[0]++; else if(ch==' ') res[1]++; else if(String.valueOf(ch).matches("^[0-9]+$"))//数字正则表达式 res[2]++; else res[3]++; } return res; } public static void main(String arg[]){ System.out.println("请输入一行内容,以回车符结尾"); Scanner scan=new Scanner(System.in); String sentence=scan.nextLine(); int[] result=num(sentence); System.out.print("该行包含的英文、空格、数字及其它字符的个数分别为:"); System.out.print(result[0]+""+result[1]+""+result[2]+""+result[3]); } }