小算法:统计一个字符串中每个字符出现的次数

统计一个字符串中每个字符出现的次数

前言:
最近在学习哈夫曼编码时,发现统计一串字符串时用到的小算法挺精妙,于是在此将其提取了出来如下:

待统计字符串:i like like like java do you like a java

代码如下:

import java.util.HashMap;
import java.util.Map;

/**
 * 统计一个字符串中每个字符出现的次数
 * @author Administrator
 *
 */
public class Main {
    
    
	public static void main(String[] args) {
    
    
		String str="i like like like java do you like a java";
		//将字符串转换为字符数组
		char[] arrStr=str.toCharArray();
		Map<Character,Integer> counts=new HashMap<Character, Integer>();
		for(char b:arrStr) {
    
    
			//遍历字符数组,第一次遍历得到时将其数量为1,再次遍历时数量自增
			Integer count=counts.get(b);
			if(count==null) {
    
    
				counts.put(b, 1);
			}else {
    
    
				counts.put(b, count+1);
			}
		}
		//遍历Map输出
		for(Map.Entry<Character, Integer> entry:counts.entrySet()) {
    
    
			System.out.println(entry.getKey()+"------>"+entry.getValue());
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_45273552/article/details/109139434