JAVA 统计字符串字母数字其他字符个数

这个初识java一定会遇到的基础题,可以参考学习下。

public class StringTest {
	public static void main(String[] args) {
		String strTest="1a2x4d _h.;q,56zx";
		StringTest.countByChar(strTest);
		StringTest.countByASCLLCode(strTest);
		StringTest.countByRegular(strTest);
	}

方法1:通过字符统计

public static void countByChar(String str){
		int numCount=0,charCount=0,otherCount=0;
		char temp;
		for (int i = 0; i < str.length(); i++) {
			temp=str.charAt(i);
			if((temp>='a' && temp<='z') ||(temp>='A' && temp<='Z')){
				charCount++;
			}else if(temp>='0' && temp<='9'){
				numCount++;
			}else{
				otherCount++;
			}
		}
		System.out.println("numCount="+numCount);
		System.out.println("charCount="+charCount);
		System.out.println("otherCount="+otherCount);
	}

方法2:通过ASCLL值统计

public static void countByASCLLCode(String str){
	int numCount=0,charCount=0,otherCount=0;
	char temp;
	for (int i = 0; i < str.length(); i++) {
		temp=str.charAt(i);
		if((temp>=97 && temp<=122) ||(temp>=65 && temp<=90)){
			charCount++;
		}else if(temp>=48 && temp<=57){
			numCount++;
		}else{
			otherCount++;
		}
	}
	System.out.println("numCount="+numCount);
	System.out.println("charCount="+charCount);
	System.out.println("otherCount="+otherCount);
}

方法3:通过正则校验

public static void countByRegular(String str){
		int numCount=0,charCount=0,otherCount=0;
		String numRegular="^[0-9]$",charRegular="^[a-zA-Z]$";
		Pattern pattern1 =Pattern.compile(numRegular);
		Pattern pattern2 =Pattern.compile(charRegular);
		char temp;
		for (int i = 0; i < str.length(); i++) {
			temp=str.charAt(i);
			if(pattern2.matcher(""+temp).matches()){
				charCount++;
			}else if(pattern1.matcher(""+temp).matches()){
				numCount++;
			}else{
				otherCount++;
			}
		}
		System.out.println("numCount="+numCount);
		System.out.println("charCount="+charCount);
		System.out.println("otherCount="+otherCount);
	}

注:
str.charAt(index) 获取指定下标字符
ASCLL表:
a-z:97-122
A-Z:65-90
0-9:48-57
正则校验:
1" : 匹 配 a − z A − Z " [ 0 − 9 ] " :匹配a-zA-Z "^[0-9]":匹配a−zA−Z"[0−9]” :匹配0-9

参考:
https://blog.csdn.net/River_Continent/article/details/79667306

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值