/**
* 统计字符串中各种类型字符个数
* @param str
* @param type
* @return 个数
*/
public static int countSumByType(String str, int type){
int count = 0;
int abccount = 0;
int numcount = 0;
int spacecount = 0;
int othercount = 0;
if(StringUtils.isEmpty(str)){
return 0;
}
char[] b = str.toCharArray();
for(int i = 0; i < b.length; i++){
if(b[i]>='a'&&b[i]<='z'||b[i]>='A'&&b[i]<='Z'){
abccount++;
}else if(b[i]>='0'&&b[i]<='9'){
numcount++;
}else if(b[i]==' '){
spacecount++;
}else{
othercount++;
}
}
if(type==1){ // 字母
count = abccount;
} else if(type==2){ // 数字
count = numcount;
} else if(type==3){ // 空格
count = spacecount;
} else if(type==0){ // 全部
count = abccount + numcount + spacecount + othercount;
}
return count;
}
测试类:
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "7只需3000元-7plus只需3500元 6s只需2000-6splus只需2200 6 只需1600-6p只需1800 5S:900-5Se:1200 国行正品 支持全国联保 支持貨捯附款 支持紛期附款 加昵称上的号咨询购 维 姓 号 K F C 3 6 2";
System.out.println("字母:" + countSumByType(str, 1));
System.out.println("数字:" + countSumByType(str, 2));
System.out.println("空格:" + countSumByType(str, 3));
System.out.println("全部:" + countSumByType(str, 0));
}
运行结果:
字母:17
数字:42
空格:18
全部:131