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
标签:JAVA,String,temp,int,otherCount,个数,charCount,str,字符串 来源: https://blog.csdn.net/qq_38708916/article/details/113620952