利用中文編碼(GB2312/GBK)中漢字區位碼範圍,對應聲母區間。非漢字(字母、符號、數字)保持原樣。
public string GetPYString(string str) {
if (string.IsNullOrEmpty(str)) return string.Empty;
StringBuilder sb = new StringBuilder();
foreach (char c in str) {
if (c >= 33 && c <= 126) { // ASCII 可見字元
sb.Append(c);
} else {
sb.Append(GetPYChar(c.ToString()));
}
}
return sb.ToString();
}
public string GetPYChar(string c) {
byte[] arr = Encoding.Default.GetBytes(c); // 系統預設編碼(通常為 GB2312/GBK)
if (arr.Length < 2) return "*"; // 非雙位元組字元
int code = (arr[0] - 160) * 256 + (arr[1] - 160); // 區位碼計算
if (code < 0xB0A1) return "*";
if (code < 0xB0C5) return "a";
if (code < 0xB2C1) return "b";
if (code < 0xB4EE) return "c";
if (code < 0xB6EA) return "d";
if (code < 0xB7A2) return "e";
if (code < 0xB8C1) return "f";
if (code < 0xB9FE) return "g";
if (code < 0xBBF7) return "h";
if (code < 0xBFA6) return "j"; // 注意:原碼此處誤為 g,實際為 j
if (code < 0xC0AC) return "k";
if (code < 0xC2E8) return "l";
if (code < 0xC4C3) return "m";
if (code < 0xC5B6) return "n";
if (code < 0xC5BE) return "o";
if (code < 0xC6DA) return "p";
if (code < 0xC8BB) return "q";
if (code < 0xC8F6) return "r";
if (code < 0xCBFA) return "s";
if (code < 0xCDDA) return "t";
if (code < 0xCEF4) return "w";
if (code < 0xD1B9) return "x";
if (code < 0xD4D1) return "y";
if (code < 0xD7FA) return "z";
return "*";
}
string name = "張三豐";
string py = GetPYString(name); // 輸出:zsf
Console.WriteLine(py);
Microsoft.International.Converters.PinYinConverter(需安裝 International Pack)