public class 统计字符存在的个数 {
String string="sdfsdfsdf sdfsd iinilgh ,mkn ,ikj";
Map<Character,Integer> map=new HashMap<>();
public Map<Character, Integer> getNum(String str){
for(int i=0;i<str.length();i++){
char c=str.charAt(i);
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}else{
map.put(c, 1);
}
}
System.out.println(map);
return map;
}
@Test
public void test1(){
getNum(string);
}
public static void main(String[] args) {
//原有长度减去替换后的长度就是该字母的个数
String str = "hello world";
int length =0;
while(str.length()>0){
String first = String.valueOf(str.charAt(0));//将第一个字母变为字符串
String newString = str.replaceAll(first, "");//将第一个字符相同的替换为空字符串
length = str.length() - newString.length();
str = newString;
System.out.print(first+":"+length+" ");
}
}
}