五十道编程小题目 --- 07 统计出其中英文字母、空格、数字和其它字符的个数 java

来源:互联网 发布:两钻淘宝店值多少钱 编辑:程序博客网 时间:2024/06/12 21:37
【程序7】 
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 

1.程序分析:利用正则表达式


import java.util.Scanner;import java.util.regex.Pattern;public class Counting {public static void counting(String str) {//char[] c = str.toCharArray();int abcCount = 0;// 英文字母个数int spaceCount = 0;// 空格个数int numCount = 0;// 数字个数int otherCount = 0;// 其他字符个数Pattern p1 = Pattern.compile("^[a-zA-Z]+$"); // 验证字母Pattern p2 = Pattern.compile("^[0-9]+$");    //验证数字Pattern p3 =  Pattern.compile("\\s+");       //验证空格String s = null;for(int i=0; i<str.length(); i++ ){s = str.substring(i,i+1);if(p1.matcher(s).matches()){abcCount++;}else if(p2.matcher(s).matches()){numCount++;}else if(p3.matcher(s).matches()){spaceCount++;}else{otherCount++;}}System.out.println("英文字母个数" + abcCount);System.out.println("空格个数" + spaceCount);System.out.println("数字个数" + numCount);System.out.println("其他个数" + otherCount);}public static void main(String[] args) {Scanner s = new Scanner(System.in);counting(s.nextLine());}}
输入:

gmgljrt4t4uerttmr;f rgerjg rg-rg gr

结果为:

英文字母个数28空格个数3数字个数2其他个数2















0 0
原创粉丝点击