1. 程式人生 > >取出一個字串中字母出現的次數。如:字串:"abcdekka27qoq" ,輸出格式為: a(2)b(1)k(2)

取出一個字串中字母出現的次數。如:字串:"abcdekka27qoq" ,輸出格式為: a(2)b(1)k(2)

package com.heima.test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;

public class Test1 {

    /**
        取出一個字串中字母出現的次數。如:字串:"abcdekka27qoq" ,輸出格式為:
        a(2)b(1)k(2)
     * @param args
     * @throws IOException 
     */
public static void main(String[] args) throws IOException { String str = "asdzxclkjoiwermsnasd12432452"; HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); char [] cc = str.toCharArray(); for (char c : cc) { if(!hm.containsKey(c)){ hm.put(c, 1
); }else{ hm.put(c, hm.get(c)+ 1); } } for (char c : hm.keySet()) { System.out.print(c+"("+hm.get(c)+")"); } FileWriter fw = new FileWriter("bbb.txt"); for (char c : hm.keySet()) { fw.write(c+"("+hm.get(c)+")"
); fw.write("\n"); } fw.close(); } }