统计一组字符串中各个单词出现的次数

用代码实现以下需求
(1)有如下字符串"If you want to change your fate I think you 
must come to the dark horse to learn java"(用空格间隔)
(2)打印格式:
to=3
think=1
you=2
//........
(3)按照上面的打印格式将内容写入到D:\\count.txt文件中(要求用高效流)

解题思路:
  1,切割字符串
  2,统计相同字符个数
  3,打印字符串    +  个数

  4,将字符串写入到  D:\\count.txt  文件中(高效流)




package HomeWork2;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;

public class Count_String {
	public static void main(String[] args) throws IOException {
		String str = "If you want to change your fate I think you must come to the dark house to learn java";
		Map<String, Integer> map = new HashMap<String, Integer>();
		String[] strArr = str.split("\\s+");
		countString(map, strArr);
		printWord(map);

	}

	/*
	 *   将字符串写入到h:\\count.txt 文件中(使用高效流) 
	 */
	public static void outputToFile(String str) throws IOException {
		BufferedOutputStream bis = new BufferedOutputStream(new FileOutputStream("h:\\count.txt", true));
		bis.write((str + "\r\n").getBytes());
		bis.close();
	}

	/*
	 *  打印字符串单词  + 个数
	 */
	public static void printWord(Map<String, Integer> map) throws IOException {
		// entrySet 方法遍历Hashmap
		for (Map.Entry<String, Integer> entry : map.entrySet()) {
			String word = entry.getKey();
			int count = entry.getValue();
			System.out.println(word + "=" + count);
			outputToFile(word + "=" + count);
		}
	}

	/*
	 *   统计切割的字符串里 各个单词出现的 次数
	 */
	public static void countString(Map<String, Integer> map, String[] strArr) {
		for (int i = 0; i < strArr.length; i++) {
			if (map.containsKey(strArr[i])) {
				map.put(strArr[i], map.get(strArr[i]) + 1);
			} else {
				map.put(strArr[i], 1);
			}
		}
	}
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值