统计出现字符的次数

1。方法一,用map。

public class Test{
public static void main(String[]args){
String s
="fsfeuofjkeulkdue";
Map
<String,Integer> map1=new HashMap<String,Integer>();
for(int i=0;i<s.length();i++){
if(map1.get(s.substring(i, i+1))==null){
map1.put(s.substring(i, i
+1), 1);
}
else{
map1.put(s.substring(i, i
+1), map1.get(s.substring(i, i+1))+1);
}
}
//输出
for(String s1:map1.keySet()){
System.out.println(s1
+map1.get(s1));
}

}
}

2.方法二,用数组。

public class StatisticsStr {

/**
* 任意一字符串, 字符串转为一字符数组, 26个英文字母出现次数的集合
*/
private static final String STR_TEMPLATE = "fdkfjejfksdfusls";
private static final char[] ch = STR_TEMPLATE.toCharArray();
private static final int[] count = new int[26];

/**
* 思路: 因为小写字母a的ascii为96,所以将每个字母减去96,从数组0开始
*
* 每出现一个字母就在相应加1
*/
public static void main(String[] args) {
for (int i = 0; i < ch.length; i++) {
int ascii = (char) ch[i] - 96;
count[ascii]
= count[ascii] + 1;
}

for (int i = 0; i < count.length; i++) {
System.out.println((
char) (i + 96) + "出现了: " + count[i]);
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值