一、题目描述
给定一个任意的字符串,统计并输出字符串中每个字符出现的次数和出现次数最多的字符。
二、解题思路
- 我们常用的字符的ASCII码是从32到127,所以我们创建一个长度为96的数组来保存32-127之间的每个字符所出现的次数。
- 然后将字符串转换为字符数组,通过增强for循环,将每个字符转换成对应的ASCII码并进行遍历。只要对应的ASCII码值在32-127,就让该字符所对应位置的数组上的元素加一。
- 如何输出数组每个索引上对应字符?由于数组的索引是从0开始,而我们要寻找的字符位于32-127,所以数组的索引加上32便是对应的字符ASCII码,通过类型转换便可以得到对应的字符。
- 寻找出现次数最多的字符的原理和寻找数组中的最大值的原理一样,先假设数组第一个元素最小并赋值给变量max,然后依次和数组中的下一个元素进行比较,如果小于下一个元素,则将下一个元素赋值给max,直到所有的元素都比较完毕,得到的max就是最大值。
三、代码示例
package com.easy.java;
/**
* @ClassName Test06
* @Description 输入一个字符串,统计每个字符出现的次数,和出现次数最多的字符。
* @Author wk
* @Date 2021/11/28 22:35
* @Version 1.0
*/
public class Test06 {
public static void main(String[] args) {
String str = "Don't be afraid to shoot a single horse. What about being alone and brave? You can cry all the way, but you can't be angry. " +
"You have to go through the days when nobody cares about it to welcome applause and flowers." +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBB";
int strArr[] = new int[96];
// 增强for循环
for (int i : str.toCharArray()) {
if (i >= 32 && i <= 127) {
strArr[i - 32]++;
}
}
for (int i = 0; i < strArr.length; i++) {
if (strArr[i] != 0) {
// 得到数组每个索引上对应的字符
char target = (char) (i + 32);
// 输出每个字符出现的次数
System.out.println(target + " ----> " + strArr[i]);
}
}
// 统计出现次数最多的字符
int max = strArr[0];
int index = 0;
for (int i = 0; i < strArr.length; i++) {
if (max < strArr[i]) {
max = strArr[i];
index = i;
}
}
if((index + 32) == 32){
System.out.println("出现次数最多的字符是:" + "空格(space)" + ",出现次数为:" + max);
}else {
System.out.println("出现次数最多的字符是:" + (char) (index + 32) + ",出现次数为:" + max);
}
}
}
四、测评结果
- 实例一:
String str = "Don't be afraid to shoot a single horse. " +
"What about being alone and brave? You can cry all the way, but you can't be angry. " +
"You have to go through the days when nobody cares about it to welcome applause and flowers." +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBB";
- 实例二
String str = "Don't be afraid to shoot a single horse. " +
"What about being alone and brave? You can cry all the way, but you can't be angry. " +
"You have to go through the days when nobody cares about it to welcome applause and flowers.";