`
tonyJ
  • 浏览: 142450 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

统计一个字符串中出现最多的字符个数

阅读更多
package date0513;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author tonyJ<br/> 2011-5-13 下午02:05:00
 */
public class Test01 {
	public static void main(String[] args) {
		countMaxStr("111dfasfdddd");
	}

	@SuppressWarnings("unchecked")
	public static void countMaxStr(String str) {
		char[] c = str.toCharArray();
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		for (int i = 0; i < c.length; i++) {
			Integer num = map.get(c[i]);
			if (num == null) {
				map.put(c[i], 1);
			} else {
				map.put(c[i], num + 1);
			}
		}

		Iterator<?> iter = map.entrySet().iterator();
		int max = 0;
		char ch = ' ';
		while (iter.hasNext()) {
			Map.Entry entry = (Entry) iter.next();
			if ((Integer) entry.getValue() > max) {
				max = (Integer) entry.getValue();
				ch = (Character) entry.getKey();
			}
		}
		System.out.println("最多的字符是:" + ch);
		System.out.println("出现的次数是:" + max);

	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics