package com.casts
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
/*
* 2.分析以下需求,並用代碼實現:
(1)利用鍵盤錄入,輸入一個字符串
(2)統計該字符串中各個字符的數量
(3)如:
用戶輸入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
程序輸出結果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)
l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
*/
public class Demo {
public static void main(String[] args) {
//鍵盤錄入字符串
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個字符串:");
//接收字符串
String str = sc.nextLine();
//用於統計字符串
String newSet = getSet(str);
System.out.println(newSet);
}
private static String getSet(String str) {
//1,將字符串轉換爲字符數組
char[] chars = str.toCharArray();
//2,創建一個map集合,將字符和出現的次數存儲到集合中
TreeMap<Character,Integer> map = new TreeMap<Character,Integer>();
//3,遍歷字符數組
for (char c : chars) {
map.put(c,map.get(c) != null ? map.get(c) : 1);
}
//4,創建StringBuffer
StringBuffer sb = new StringBuffer();
//5,遍歷map集合
for(Map.Entry<Character, Integer> entry : map.entrySet()){
sb.append(entry.getKey()).append("(").append(entry.getValue()).append(")");
}
//6,返回StringBuffer的字符串變現形式
return sb.toString();
}
}
鍵盤錄入並統計該字符串中各個字符的數量
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.