一、分别统计字符串中出现的所有字符的个数
实例代码:
/**
* 统计字符串中出现的所有字符的个数;
*/
public static void classAllCount(){
String str="6hj$#%&*()IGR哈哈哈GjI6hj$#%&@&**()^$j@@$#^&)(^&$6hj$#%&(RG@@IIjh6h哈j$#%&456465";
Map<Character, Integer> map=new HashMap<>();
for(int i=0;i<str.length();i++){
Character a=str.charAt(i);
Integer count=map.get(a);
if(count==null){
count=1;
map.put(a, count);
}
else{
count+=1;
map.put(a, count);
}
}
System.out.println("1. "+map.toString());
}
二、分别统计字符串中的字母、汉字、数字个数
实例代码:
/**
* 分别统计字符串中的字母、汉字、数字各有多少个;
*/
public static void classiFiedCount(){
String str2="福建省HFSD4655DSAJKD的接口返回dfh465sjfh到数据库";
int en=0;
int ch=0;
int num=0;
for(int i=0;i<str2.length();i++){
char b=str2.charAt(i);
if((b>='A'&&b<='Z')||(b>='a'&&b<='z')){
en+=1;
}else if(b>='0'&&b<='9'){
num+=1;
}else{
ch+=1;
}
}
System.out.println("2. 字母:"+en+"\t汉字:"+ch+"\t数字:"+num);
}
三、测试(main方法)
public static void main(String[] args) {
classAllCount();
classiFiedCount();
}
四、打印结果
1. {@=5, #=5, $=7, %=4, &=7, G=3, h=5, (=4, 哈=4, )=3, I=4, j=7, *=3, R=2, 4=2, 5=2, 6=6, ^=3}
2. 字母:17 汉字:12 数字:7