中文字在系統內部以 區位碼 (GB2312 編碼) 儲存:兩個位元組,高位 = 區碼 (0xA1~0xF7),低位 = 位碼 (0xA1~0xFE)。依區位碼範圍對應拼音首字母分區表,即可快速推導首字母,無需龐大字典。
public static string GetChineseSpell(string strText) {
StringBuilder sb = new StringBuilder();
foreach (char c in strText) sb.Append(GetInitial(c));
return sb.ToString();
}
public static string GetInitial(string cnChar) {
byte[] bytes = Encoding.Default.GetBytes(cnChar); // 系統預設編碼 (通常 GB2312/CP936)
if (bytes.Length != 2) return cnChar; // 非漢字直接返回
int zone = bytes[0]; int pos = bytes[1];
int code = (zone << 8) + pos; // 合併為單一整數比較
// 拼音首字母分區上限編碼表 (A~Z)
int[] areaCode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614,
48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622,
50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980,
53689, 54481 }; // 共 26 筆,對應 A~Z
for (int i = 0; i < 26; i++) {
int max = (i == 25) ? 55290 : areaCode[i + 1];
if (areaCode[i] <= code && code < max)
return ((char)('A' + i)).ToString();
}
return "*"; // 未匹配區間
}
GetChineseSpell("中國") // 返回 "ZG"
GetChineseSpell("Hello世界") // 返回 "HelloSJ"
注意:需確保執行環境 Encoding.Default 為 GB2312 相容編碼 (中文 Windows 預設滿足);.NET Core 跨平台時需顯式指定 Encoding.GetEncoding("GB2312")。