1. 程式人生 > >java字串去重寫檔案學習筆記

java字串去重寫檔案學習筆記

  /**
     * * 使用Scanner從鍵盤讀取一行輸入,去掉其中重複字元, 打印出不同的那些字元
     * aaaabbbcccddd
     *
     * 分析:
     * 1,建立Scanner物件
     * 2,建立HashSet物件,將字元儲存,去掉重複
     * 3,將字串轉換為字元陣列,獲取每一個字元儲存在HashSet集合中,自動去除重複
     * 4,遍歷HashSet,列印每一個字元
     */
    @Test
    public void jihe9() {
        String ss = "aaaabbbcccdddwerwrweddcsecsefwewe";
        HashSet<Character> hs = new HashSet<>();
        char[] chars = ss.toCharArray();
        for (char c : chars) {
            hs.add(c);
        }
        System.out.println(hs);
        StringBuilder stringBuilder = new StringBuilder();
        for (Character s : hs) {
            stringBuilder.append(s.toString());
        }
        System.out.println(stringBuilder);
        System.out.println("88888888888888888888888888888");
        HashMap<Character, Integer> map = new HashMap<>();
        for (char c : chars) {
            map.put(c, !map.containsKey(c) ? 1 : map.get(c) + 1);
        }
        for (Character c : map.keySet()) {
            System.out.println(c+"="+map.get(c));
        }
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("x.txt"));
            for (Map.Entry<Character, Integer> m : map.entrySet()) {
                bufferedWriter.write(m.getKey() + ":" + m.getValue()+",");
            }
            System.out.println("寫入成功!!");
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }