統計字串字元個數

想不起来好名字發表於2024-03-17
import java.security.Key;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

public class Main {
public static <scanner> void main(String[] args) {
System.out.println("請輸入一個字串");
Scanner sc = new Scanner(System.in);
String S = sc.next();

TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
Integer i1 = tm.get(c);
if (i1 == null) {
tm.put(c, 1);
} else {
i1++;
tm.put(c, i1);
}


}

StringBuilder stringBuilder = new StringBuilder();
Set<Character> characters = tm.keySet();
for (char c : characters) {
int m = tm.get(c);
stringBuilder.append(c).append("(").append(m).append(")");


}
String string = stringBuilder.toString();
System.out.println(string);


}
}

相關文章