GB2312 中漢字編碼為雙位元組,區碼 16-87,位碼 1-94。依據區位碼範圍對應首字母 (如 1601-1636 → A)。
using System;
using System.Text;
public static class ChineseSpell
{
// 區位碼起始值對應首字母 (GB2312)
private static readonly (int Zone, int Position, char Letter)[] _map = new[]
{
(16, 01, 'A'), (16, 37, 'B'), (17, 09, 'C'), (17, 38, 'D'), (18, 01, 'E'),
(18, 26, 'F'), (18, 55, 'G'), (19, 20, 'H'), (19, 53, 'J'), (20, 06, 'K'),
(20, 37, 'L'), (21, 01, 'M'), (21, 29, 'N'), (21, 55, 'O'), (22, 01, 'P'),
(22, 28, 'Q'), (22, 55, 'R'), (23, 01, 'S'), (23, 38, 'T'), (24, 01, 'W'),
(24, 20, 'X'), (24, 43, 'Y'), (25, 01, 'Z')
};
///
/// 取得單一中文字的拼音首字母 (大寫),非中文回傳原字元
///
public static char GetInitial(char ch)
{
// 嘗試 GB2312 編碼
byte[] bytes;
try { bytes = Encoding.GetEncoding("GB2312").GetBytes(new[] { ch }); }
catch { return ch; } // 不支援字元
if (bytes.Length != 2) return ch; // 非雙位元組漢字
int zone = bytes[0];
int pos = bytes[1];
// 區位碼有效範圍檢查
if (zone < 16 || zone > 87 || pos < 1 || pos > 94) return ch;
// 線性查找 (陣列小,效能足夠)
for (int i = _map.Length - 1; i >= 0; i--)
{
if (zone > _map[i].Zone || (zone == _map[i].Zone && pos >= _map[i].Position))
return _map[i].Letter;
}
return ch; // 理論不會到達
}
///
/// 取得字串的拼音首字母縮寫
///
public static string GetInitials(string text)
{
if (string.IsNullOrEmpty(text)) return "";
var sb = new StringBuilder(text.Length);
foreach (char c in text) sb.Append(GetInitial(c));
return sb.ToString();
}
}
// 使用範例
class Program
{
static void Main()
{
Console.WriteLine(ChineseSpell.GetInitials("中國人民")); // ZGR
Console.WriteLine(ChineseSpell.GetInitial("漢")); // H
Console.WriteLine(ChineseSpell.GetInitial('A')); // A
}
}
| 項目 | 說明 |
|---|---|
| 編碼 | 必須用 **GB2312** (代碼頁 936),UTF-8/Unicode 無區位碼對應關係 |
| 非漢字 | 英文、數字、符號直接回傳原字元 |
| 生僻字/擴展區 | GB2312 不支援 (如 𠮷、𫖯),會拋出編碼例外或回傳原字元 |
| 多音字 | 首字母演算法無法區分多音字 (如「行」xing/hang 同為 X),接受近似 |
| 效能 | 單字 O(1) 查表,字串 O(n),極快 |
// Windows 10+ / .NET 6+ 可用系統 API 取得完整拼音 (含聲調)
using System.Globalization;
// 目前 .NET 標準庫無內建拼音 API,需 P/Invoke GetPhonetic 或第三方庫 (PinYin, Chinese.NET)
基於 **GB2312 區位碼區間對照** 的首字母演算法,是無外部依賴、效能極佳、部署簡單的方案。適用於**排序索引、輸入法提示、通訊錄分組**等不需精確聲調的場景。若需完整拼音、聲調、多音字處理,請引入成熟第三方庫 (如 `PinYin`、`Chinese.NET`)。