怎样统计一串字符串字符出现的次数java?

2025-03-26 03:17:58
推荐回答(1个)
回答1:

直接上代码
import java.util.*;
public class Test {
public static void main(String args[]){
String s = "abcdad"; //待测试的字符串
Map result = getCharMaps(s);
System.out.println(result);//打印出字符串中各字符出现的次数!

}
public static Map getCharMaps(String s) {
Map map = new HashMap();
for(int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
Integer count = map.get(c);
map.put(c, count == null ? 1 : count + 1);
}
return map;

}

}