欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-01-24 12:05:22
...
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);

	}
}

相关标签: Java C C++ C#