例题:
代码演示:
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
public class StringDemo1 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入一个字符串");
String s=scanner.nextLine();
HashMap<Character,Integer> hashMap=new HashMap<>();
for (int i=0;i<s.length();i++){
char key=s.charAt(i);
Integer value=hashMap.get(key);
if (value==null){
hashMap.put(key,1);
}else {
value++;
hashMap.put(key,value);
}
}
StringBuilder stringBuilder=new StringBuilder();
Set<Character> set=hashMap.keySet();
for (Character key:set){
stringBuilder.append(key).append("(").append(hashMap.get(key)).append(")");
}
String s1=stringBuilder.toString();
System.out.println(s1);
}
}
输出:
请输入一个字符串
aaabababba
a(6)b(4)