用代码实现以下需求
(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); } } } }