传入一个字符串,如何获得这个字符串中所有字符出现的个数

package cn.com.lianxi;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class demo {

public static void main(String[] args) {
Map<String,Integer> map=getcount("abcdbcd");
for(String s:map.keySet()){
System.out.println(s+":"+map.get(s));
}
}

public static Map<String,Integer> getcount(String str){
String[] ch=str.split("");//分隔字符串,获得字符串数组
List<String> list=new ArrayList<String>();//用于记录出现的字符
list.add("");
int count;
Map<String,Integer> map=new HashMap<String, Integer>();
outer:
for(int i=0;i<ch.length;i++){
count=0;//记录字符出现的个数,每次循环前需要重置为0
String s=ch[i];//获得字符
//判断字符是不是前面出现过,如果是的话,就跳过这次循环
for(int j=0;j<list.size();j++){
if(s.equals(list.get(j))){
continue outer;//跳出最外面的循环,继续执行下一个
}
}
//匹配字符出现的个数,count是记录个数的
for(int m=0;m<ch.length;m++){
if(s.equals(ch[m])){
count++;
}
}
map.put(s, count);//存储数据
list.add(s);//获取每次的字符,用于过滤掉后面出现的相同字符

}

return map;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值