中文字元在 Unicode 中主要集中於 CJK Unified Ideographs 區塊:U+4E00 ~ U+9FFF。透過 Char.ConvertToUtf32 取得字元的 Unicode 碼點,判斷是否落於此範圍即可。
protected bool IsChineseLetter(string input, int index) {
if (string.IsNullOrEmpty(input) || index < 0 || index >= input.Length) return false;
int codePoint = Char.ConvertToUtf32(input, index); // 正確處理代理對
const int chFrom = 0x4E00; // 19968
const int chEnd = 0x9FFF; // 40959
return codePoint >= chFrom && codePoint <= chEnd;
}
Char.ConvertToUtf32(string, index):正確處理補充字元(Surrogate Pair),比 (int)char 更可靠0x4E00~0x9FFF 涵蓋 20,992 個常用漢字(含繁簡)FF00~FFEF)、注音符號、擴展區漢字(20000~2FFFF)public static bool IsChineseCharExtended(string input, int index) {
if (string.IsNullOrEmpty(input) || index < 0 || index >= input.Length) return false;
int cp = Char.ConvertToUtf32(input, index);
// 基本區 + 擴展區A + 兼容區 + 全形標點/符號
return (cp >= 0x4E00 && cp <= 0x9FFF) || // CJK Unified Ideographs
(cp >= 0x3400 && cp <= 0x4DBF) || // CJK Extension A
(cp >= 0x20000 && cp <= 0x2A6DF) || // CJK Extension B
(cp >= 0x2A700 && cp <= 0x2B73F) || // CJK Extension C
(cp >= 0x2B740 && cp <= 0x2B81F) || // CJK Extension D
(cp >= 0x2B820 && cp <= 0x2CEAF) || // CJK Extension E
(cp >= 0xF900 && cp <= 0xFAFF) || // CJK Compatibility
(cp >= 0xFF00 && cp <= 0xFFEF); // Halfwidth and Fullwidth Forms (全形標點)
}
public static bool ContainsChinese(string input) {
if (string.IsNullOrEmpty(input)) return false;
for (int i = 0; i < input.Length; ) {
int cp = Char.ConvertToUtf32(input, i);
if (cp >= 0x4E00 && cp <= 0x9FFF) return true;
i += Char.IsSurrogatePair(input, i) ? 2 : 1; // 正確推進索引
}
return false;
}
public static int CountChineseChars(string input) {
int count = 0;
for (int i = 0; i < input.Length; ) {
int cp = Char.ConvertToUtf32(input, i);
if (cp >= 0x4E00 && cp <= 0x9FFF) count++;
i += Char.IsSurrogatePair(input, i) ? 2 : 1;
}
return count;
}
private static readonly Regex ChineseRegex = new Regex(@"\p{IsCJKUnifiedIdeographs}", RegexOptions.Compiled);
public static bool IsChineseRegex(string input) => ChineseRegex.IsMatch(input);
\p{IsCJKUnifiedIdeographs} 為 Unicode 類別名稱,可讀性高、效能佳(靜態編譯)。
// 基本區
IsChineseLetter("中", 0) // true
IsChineseLetter("文", 0) // true
// 邊界
IsChineseLetter("一", 0) // true (0x4E00)
IsChineseLetter("龟", 0) // true (0x9FFF)
// 非中文
IsChineseLetter("A", 0) // false
IsChineseLetter("1", 0) // false
IsChineseLetter("。", 0) // false (全形句號 0x3002)
// 代理對 (Ext-B) "𠀀" (U+20000)
IsChineseLetter("𠀀", 0) // false (基本版) / true (擴展版)