Think In Java Chapter 18 IO系统 练习17 计算文件中字符出现次数

 * 使用TextFile和Map<Character,Integer> 创建一个应用程序,
 * 它可以对在一个文件中的所有不同的
 * 字符出现的次数进行计数。

package chapter18;

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

import net.mindview.util.TextFile;

/**
 * @功能说明 :
 * 使用TextFile和Map<Character,Integer> 创建一个应用程序,
 * 他可以对在一个文件中的所有不同的
 * 字符出现的次数进行计数。
 * @author shaochong
 * @Date  2014年12月23日 下午8:55:42
 */
public class test17 {

	public static void main(String[] args) {
		String filename = "e:\\data\\data17.txt";
		Map<Character, Integer> map = new HashMap<Character,Integer>();
		String textstr = TextFile.read(filename);
		
		for (int i = 0; i < textstr.length(); i++) {
			Object k = map.get(textstr.charAt(i));
			if(k==null)
				map.put(textstr.charAt(i), 1);
			else {
				int num = (Integer)k + 1;
				map.replace(textstr.charAt(i),num);
			}
		}
		
		Set<Character> set = map.keySet();
		for(Iterator it = set.iterator(); it.hasNext();){
			char ch = (char) it.next();
			int num = map.get(ch);
			System.out.println("'"+ch+"' :" + num );
		}
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值