可用ascii值作数组下标直接计数,适用于0–127或0–255范围;支持unicode需预处理;统计英文字母可压缩至26位,分组计数(大小写、数字)可提升效率与清晰度。
可以用字符的 ascii 值作为数组下标,直接映射到计数位置,适用于 ascii 字符(0–127)或扩展 ascii(0–255)范围;若需支持 unicode 中文等宽字符,则需额外处理(如预处理转码或限定输入范围),但核心思路不变:用数组索引代替键,用元素值代替频次。
适用场景与前提限制
该方法高效、轻量,但依赖字符取值可枚举且范围可控:
- 仅统计英文大小写字母('a'–'z', 'A'–'Z'):共 52 个,可建长度 52 的数组,或统一转小写后用 26 位
- 统计所有 ASCII 可见字符(32–126):长度 95,下标 = ch - 32
- 统计全部标准 ASCII(0–127):直接声明 int[] count = new int[128],访问 count[ch] 即可(ch 自动转为 int)
- 不适用于任意 Unicode 字符(如中文“你好”),因其码点可达 65535+,直接开数组浪费且不可行
基础实现:ASCII 全范围计数器组
对字符串中每个字符,以其 ASCII 值为下标累加:
String s = "hello world";
int[] count = new int[128]; // 覆盖标准 ASCII
<p>for (char c : s.toCharArray()) {
if (c </p><p>// 打印非零项
for (int i = 0; i 0) {
System.out.println("'" + (char)i + "' → " + count[i]);
}
}</p>
优化变体:仅统计字母(忽略大小写)
减少空间占用,提升缓存友好性:
- 声明 int[] count = new int[26]
- 遍历中将字符转为小写:int idx = Character.toLowerCase(c) - 'a'
- 检查 idx >= 0 && idx 再计数,跳过空格、数字、标点
示例片段:
int[] letterCount = new int[26];
for (char c : "Hello, World! 123".toCharArray()) {
char lower = Character.toLowerCase(c);
int idx = lower - 'a';
if (idx >= 0 && idx <h3>扩展:多个独立计数器(计数器组)</h3><p>若需同时统计不同类别(如:大写字母、小写字母、数字),可定义多个数组:</p><pre class="brush:java;toolbar:false;">int[] upper = new int[26]; // A-Z
int[] lower = new int[26]; // a-z
int[] digit = new int[10]; // 0-9
<p>for (char c : input.toCharArray()) {
if (c >= 'A' && c = 'a' && c = '0' && c </p><p>这种分组方式逻辑清晰、无哈希开销,适合嵌入式、高频短文本或教学演示等对 Map 有规避需求的场景。</p>Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











