以下方法是手写输入的,如有编译问题,请手动更改
1.方法一:
public static void getCharAndMaxCount(String str) {
str = "www.test.com";
// 将字符串转换成字符数组(避免转成字符串数组的第一个字符为null)
char[] charArr = str.toCharArray();
// 将字符串的每个字符放到map中,key:字符--value:出现的次数
Map<Object,Integer> map = new HashMap<Object,Integer>();
for (int i = 0, j = charArr.length; i < j; i++) {
if (map.containsKey(charArr[i])) {
// map中存在某个字符时,该字符的出现次数+1
map.put(charArr[i], Integer.parseInt(map.get(charArr[i]).toString()) + 1);
} else {
// map中不存在某个字符时,将该字符添加并设置出现次数为1
map.put(charArr[i],1);
}
}
int maxNum = Collections.max(map.values());// 取出map中的所有value的最大值
for (Entry<Object,Integer> e : map.entrySet()) {
if (e.getValue() == maxNum) {
System.out.printLn("字符:"+e.getKey()+" 出现的次数最多,为:"+e.getValue());
}
}
}
2.方法二:
public static voie getCharAndMaxCount(String str) {
str = "www.test.com";
// 将str转成字符串数组
str.replace(".","");// 去掉字符串中的点号
String[] strArr = str.split("");
char temp;
// -----
Map<Object,Integer> map = new HashMap<>();
for (int i=0,j=strArr.length; i < j; i++) {
// 此处要加非空判断,否则会爆出异常
if (strArr[i] != null && !"".equals(strArr[i])) {
temp = strArr[i].charAt(0);
if (map.containsKey(temp)) {
map.put(temp, Integer.parseInt(map.get(temp).toString()) + 1);
} else {
map.put(temp,1);
}
}
}
int maxNum = Collections.max(map.values);
for (Entry<Object.Integer> e : map.entrySet()) {
if (e.getValue() == maxNum) {
System.out.println("出现次数最多的字符是:"+e.getKey()+" ,出现数:"+e.getValue());
}
}
}