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

package com.renshan.timi.collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo {
	// 统计一个字符串中相应字符出现的次数
	public static void main(String[] args) {
		//
		System.out.println("测试结果:");
		String s = "2,1,7,11,4,1,2,11,15,1,7,11,15,1,4,11,15,1,7,13,15,1,7,11,15,1,7,12,15,3,1,7,11,15,1,7,9,1,7,11,15,7,1,2,3,1,7,11,1,7,11,15";
		// 调用自定义方法来 统计相应字符出现的次数
		counts(s);
	}

	private static void counts(String s) {
		// 定义 一个容器
		TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
		// 将这TreeMap中的key全部取出来,然后储存到set集合中去
		Set<String> st = tm.keySet();
		// 将所需要统计的字符串转换成一个字符数组
//		char[] c = s.toCharArray();
		String[] c = s.split(",");
		// 通过for循环逐一统计每个字符出现的次数
		for (int x = 0; x < c.length; x++) {
			if (!st.contains(c[x])) {
				tm.put(c[x], 1);
			} else {
				tm.put(c[x], tm.get(c[x]) + 1);
			}
		}
		// 调用自定义方法在控制台上输出统计信息
		printMapDemo(tm);
	}

	private static void printMapDemo(TreeMap<String, Integer> tm) { 
		Set<String> st = tm.keySet();
		Iterator<String> ti = st.iterator();
		for (; ti.hasNext();) {
			String key = ti.next();
			System.out.println(key + "(" + tm.get(key) + ")");
		}
	}
}

 控制台打印:

测试结果:

1(13)

11(9)

12(1)

13(1)

15(9)

2(3)

3(2)

4(2)

7(11)

9(1)

猜你喜欢

转载自985571285.iteye.com/blog/2427744