count_chars
count_chars(string $string, int $mode = 0): array|string
按字节统计字符串:mode 0 全表/1 仅出现/2 仅未出现/3 出现字符字符串/4 未出现字符字符串——256 槽字节直方图。
C C23
#include <stdio.h>
/* PHP mode 0 构建的字节直方图:256 个计数器 */
int main(void) {
const char *s = "hello";
int counts[256] = { 0 }; /* 必须清零! */
for (int i = 0; s[i]; i++) counts[(unsigned char)s[i]]++;
printf("%d %d %d\n", counts['h'], counts['l'], counts['z']);
return 0;
}
1 2 0
C++ C++26
#include <iostream>
#include <map>
#include <string>
int main() {
std::string s = "hello";
std::map<char, int> counts; /* 键保持有序——输出确定 */
for (char c : s) counts[c]++;
for (const auto& [ch, n] : counts)
std::cout << ch << "=" << n << "\n";
return 0;
}
e=1 h=1 l=2 o=1
C# v11.0.100
using System.Linq;
class MainClass {
static void Main() {
string s = "hello";
// GroupBy 按字符计数;OrderBy 保证输出确定
var parts = s.GroupBy(c => c)
.OrderBy(g => g.Key)
.Select(g => g.Key + "=" + g.Count());
System.Console.WriteLine(string.Join(" ", parts));
}
}
e=1 h=1 l=2 o=1
Go v1.27.4
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
s := "hello"
counts := map[byte]int{}
for i := 0; i < len(s); i++ {
counts[s[i]]++
}
// map 遍历顺序随机——排序键后输出才稳定
keys := make([]byte, 0, len(counts))
for k := range counts {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%c=%d", k, counts[k]))
}
fmt.Println(strings.Join(parts, " "))
}
e=1 h=1 l=2 o=1
Java v27.0.1
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) {
String s = "hello";
int[] counts = new int[256]; // Java 自动清零
for (int i = 0; i < s.length(); i++) counts[s.charAt(i)]++;
// 像 PHP 的 mode 0 一样扫全表
List<String> parts = new ArrayList<>();
for (int b = 0; b < 256; b++)
if (counts[b] > 0) parts.add((char) b + "=" + counts[b]);
System.out.println(String.join(" ", parts));
}
}
e=1 h=1 l=2 o=1
JavaScript v26.13.1
const s = "hello";
const counts = {};
for (const ch of s) counts[ch] = (counts[ch] ?? 0) + 1;
// 对象键序:插入序——排序后输出才确定
console.log(
Object.keys(counts).sort().map(k => `${k}=${counts[k]}`).join(" ")
);
e=1 h=1 l=2 o=1
PHP v8.6.0
$s = "hello";
echo json_encode(count_chars($s, 1)), "\n"; // 字节 => 次数,仅出现的
echo count_chars($s, 3), "\n"; // 出现的字符排成字符串
echo strlen(count_chars($s, 4)), "\n"; // 256 - 4 个未出现 = 252
$t = count_chars($s, 0); // 全 256 槽表
echo $t[ord("h")], " ", $t[ord("z")], "\n"; // 1 0
{"101":1,"104":1,"108":2,"111":1}
ehlo
252
1 0
Python v3.15.2
from collections import Counter
s = "hello"
c = Counter(s)
# Counter 与 PHP 的 mode 1 完全对应:只有出现的项,带次数
print(dict(sorted(c.items())))
print("".join(sorted(c))) # mode 3 等价物
print(len(c)) # 去重个数
{'e': 1, 'h': 1, 'l': 2, 'o': 1}
ehlo
4
Rust v1.99.1
use std::collections::BTreeMap;
fn main() {
let s = "hello";
let mut counts: BTreeMap<char, i32> = BTreeMap::new();
for c in s.chars() {
*counts.entry(c).or_insert(0) += 1;
}
// BTreeMap 键天然有序——构造上就确定
let parts: Vec<String> = counts
.iter()
.map(|(ch, n)| format!("{}={}", ch, n))
.collect();
println!("{}", parts.join(" "));
}
e=1 h=1 l=2 o=1
TypeScript v26.13.1
const s = "hello";
const counts: Record<string, number> = {};
for (const ch of s) counts[ch] = (counts[ch] ?? 0) + 1;
// 插入序不是确定性保证——排序后输出才稳定
console.log(
Object.keys(counts).sort().map(k => `${k}=${counts[k]}`).join(" ")
);
e=1 h=1 l=2 o=1
语言差异说明
C:int counts[256] = {0} 就是 PHP mode 0 的本体(示例)——字节直方图是 C 最自然的统计形态;(unsigned char) 转换防符号扩展 UB;必须清零,否则栈上垃圾值直接进结果。
C++:std::map<char,int>(示例)键序确定;要 PHP 的 256 全表形态用 std::array<int,256>;char 若有符号,下标前同样转 unsigned char。
C#:LINQ GroupBy + OrderBy(示例);C# 字符串是 UTF-16 code unit,GroupBy(c => c) 按字符非字节——比 PHP 的字节视角更接近「字符」直觉;System.Collections.Concurrent 版本适合并行。
Go:map[byte]int + 排序(示例)——Go map 遍历乱序必须排序;for range s 按字节(ASCII 安全),Unicode 需 for _, r := range s 按 rune。
Java:int[256] 数组 + 全表扫描(示例)——与 PHP mode 0 同构;Java char 是 UTF-16,超出 BMP 的字符会拆代理对——真 Unicode 统计用 HashMap<Character,Integer>。
JavaScript:手写对象计数(示例);?? 处理首次出现;JS 字符串按 code unit 迭代,emoji 等 astral 字符拆对,用 for...of 按 code point;无内建 Counter。
PHP:五模式全谱(示例覆盖 0/1/3/4):mode 0 全 256 槽表、1 仅出现、2 仅未出现、3/4 字符串形态;字节视角——UTF-8 多字节字符按字节拆计,中文统计请用 mb_strlen/mb 系;mode 1 的键是字节码(ASCII 可读、高位不可读),json_encode 后键变字符串数字。
Python:collections.Counter 是 mode 1 的完美对应(示例);Counter 无 mode 0 形态(只有出现的键);most_common(n) 频次排序是 Counter 独有能力;Python 按 code point,无字节视角混淆。
Rust:BTreeMap 键天然有序(示例),HashMap 则需排序;entry().or_insert(0) 是惯用计数模式;chars() 按 code point 与 PHP 字节视角不同。
TypeScript:同 JS(示例);Record<string, number> 类型收口;与 JS 相同的 code point 迭代差异适用于 emoji。