天天看點

黑馬程式員——求字元串中每個字母出現的次數

                     本人源碼:

import java.util.Comparator;

import java.util.Iterator;

import java.util.Set;

import java.util.TreeMap;

public class String_num {

  public static void main(String[] args) {

  String str="abcedfa";//随便定義字元串

  shuZu(str);//用數組方法實作

  System.out.println();

  System.out.println("---------------------------------------");

  hashMap(str);//用集合方式實作

  }

  public static void shuZu(String str){

   char[]str_ch=str.toCharArray();//把字元串轉換為字元數組

   char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l',

     'm','n','o','p','q','r','s','t','u','v','w','x','y','z'};//定義26個字母字元數組

   int num[]=new int[26];//定義一個長度為26的整形數組用來為每個字母計數

   for (int i = 0; i < str_ch.length; i++) {

    for (int j = 0; j < ch.length; j++) {

     if(ch[j]==str_ch[i]){//兩層for循環進行比對

      num[j]++;//計數

     }

    }

   }

   for (int i = 0; i < num.length; i++) {

    if(num[i]!=0){//如果等于0就是在字元串中沒有出現過

     System.out.print(ch[i]+"["+num[i]+"], ");//列印

    }

   }

  }

  public static void hashMap(String str){

   TreeMap<Character,Integer> map=new TreeMap<Character,Integer>();

   for (int i = 0; i < str.length(); i++) {

    if(!map.containsKey(str.charAt(i))){//這裡也可以把str轉換成字元數組

     map.put(str.charAt(i),1);

    }else{

     int num=map.get(str.charAt(i));

     num+=1;

     map.put(str.charAt(i),num);

    }

   }

   Set<Character> set=map.keySet();

   Iterator<Character> iter=set.iterator();

   while(iter.hasNext()){

    char a=iter.next();

    System.out.print(a+"["+map.get(a)+"], ");

   }

  }

}

//比較器用于二叉樹

class MyComparator implements Comparator<Character>{

 public int compare(Character c1, Character c2) {

  int num=new Character(c1).compareTo(new Character(c2));

  return num;

 }

}

運作結果: a[2], b[1], c[1], d[1], e[1], f[1],

---------------------------------------

a[2], b[1], c[1], d[1], e[1], f[1],