package MuMu.homework.day24;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeMap;
public class Demo01 {
public static void main(String[] args) throws IOException {
/* 用代码实现以下需求
(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:
* 将字符串经过空格分隔,存入ArrayList集合中
* 再存入HashSet集合中,遍历HashSet集合,并统计个数,打印
* 写入指定文件:在第二步的输出语句下直接写入到指定的文件中
*
* 思路2:
* 使用集合
*/
String s = "If you want to change your fate I think you must come to the dark horse to learn java";
//思路1:
// method01(str);
// method02(str);
//思路2:
String[] str = s.split("[ ]+");
TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
for(String ss : str){
tm.put(ss, tm.containsKey(ss)?tm.get(ss)+1:1);
}
Set<String> keySet = tm.keySet();
BufferedWriter bfw = new BufferedWriter(new FileWriter("D:\\count.txt"));
for(String ss : keySet){
System.out.println(ss+"="+tm.get(ss));
bfw.write(ss+"="+tm.get(ss));
bfw.newLine();
}
bfw.close();
}
public static void method01(String str) {
String[] split = str.split("[ ]+");
ArrayList<String> al = new ArrayList<String>();
for(int i=0;i<split.length;i++){
al.add(split[i]);
}
HashSet<String> hs = new HashSet<String>();
hs.addAll(al);
for(String s : hs){
int count=0;
for(String ss : al){
if(ss.equals(s)){
count++;
}
}
System.out.println(s+"="+count);
}
}
public static void method02(String str) throws IOException {
FileWriter fr = new FileWriter("D:\\count.txt",true);
String[] split = str.split("[ ]+");
ArrayList<String> al = new ArrayList<String>();
for(int i=0;i<split.length;i++){
al.add(split[i]);
}
HashSet<String> hs = new HashSet<String>();
hs.addAll(al);
for(String s : hs){
int count=0;
for(String ss : al){
if(ss.equals(s)){
count++;
}
}
// System.out.println(s+"="+count);
fr.write(s+"="+count+"\r\n");//换行也可以使用 fr.newLine();
fr.flush();
}
fr.close();
}
}
|
|