统计一个字符串中数字、字母、空格和其他字符的个数

public class CalCharNumbers {
	public static void main(String[] args) {
		System.out.println("请输入一个字符串:");
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();//这里必须要用sc.nextLine();在Java中输入字符串还可以用sc.next();但是这种方式读到空格就会停止
		int alphaNum = 0;
		int spaceNum = 0;
		int digtNum = 0;
		int otherNum = 0;
		for(int i=0;i<str.length();i++){
			if(str.charAt(i)>='0'&&str.charAt(i)<='9'){
				digtNum++;
			}else if((str.charAt(i)>='a'&&str.charAt(i)<='z')||(str.charAt(i)>='A'&&str.charAt(i)<='Z')){
				alphaNum++;
			}else if(str.charAt(i)==' '){
				spaceNum++;
			}else{
				otherNum++;
			}
		}
		System.out.println("字母:"+alphaNum+",数字:"+digtNum+",空格:"+spaceNum+",其他字符:"+otherNum);
	}
}

用正则表达式实现如下:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//	统计一个字符串中字母、空格、数字和其他字符的个数
public class CalCharNumbers {
	public static void main(String[] args) {
		System.out.println("请输入一个字符串:");
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		String regex1 = "[a-z|A-Z]";
		String regex2 = "[0-9]";
		CalCharNumbers c = new CalCharNumbers();
		int a1 = c.string(s, regex1);
		System.out.println("数字的个数:"+a1);
		int a2 = c.string(s, regex2);
		System.out.println("字母的个数:"+a2);
		int a3 = c.string(s, " ");
		System.out.println("空格的个数:"+a3);
		int a4 = s.length()-a1-a2-a3;
		System.out.println("其他字符的个数:"+a4);
	}
	 public int string(String s, String pattern){
		    Pattern p = Pattern.compile(pattern);//将给定的正则表达式编译到模式中。
		    Matcher m = p.matcher(s);//创建匹配给定输入与此模式的匹配器。
		    int i = 0;
		    while (m.find()) {//尝试查找与该模式匹配的输入序列的下一个子序列。
		      i++;
		    }
		    return i;
		  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值