問題描述
"fdgavcbsacdfs" 獲取該字符串中,每一個字母出現的次數。
要求打印結果是:a(2)b(1)...;
容器的選擇
由於字母和次數之間存在着映射的關係。而且這種關係很多。
很多就需要存儲,能存儲映射關係的容器有數組和Map集合。
關係一方式有序編號嗎?沒有!
那就是使用Map集合。 又發現可以保證唯一性的一方具備着順序如 a b c ...
所以可以使用TreeMap集合。
算法思想
1,因爲操作的是字符串中的字母,所以先將字符串變成字符數組。
2,遍歷字符數組,用每一個字母作爲鍵去查Map集合這個表。 如果該字母鍵不存在,就將該字母作爲鍵 1作爲值存儲到map集合中。如果該字母鍵存在,就將該字母鍵對應值取出並+1,在將該字母和+1後的值存儲到map集合中,鍵相同值會覆蓋。這樣就記錄住了該字母的次數.
3,遍歷結束,map集合就記錄所有字母的出現的次數
實現代碼
public static void main(String[] args) {
System.out.println("請輸入字符串:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
for(int i=0;i<str.length();i++)
{
//取出字符串中的每個字符與表進行比較
if(hm.containsKey(str.charAt(i)))
{
int count = hm.get(str.charAt(i));
count++;
hm.put(str.charAt(i),count);
}
else
hm.put(str.charAt(i),1);
}
//通過迭代來得到題目所要求的格式
Iterator<Character> it = hm.keySet().iterator();
while (it.hasNext())
{
Character key = it.next();
Integer value = hm.get(key);
System.out.print(key+"("+value+")");
}
}