判斷一個字符是否是漢字一般有三種方法,第1種用 ASCII 碼判斷(在 ASCII碼錶中,英文的範圍是0-127,而漢字則是大於127,根據這個範圍能夠判斷),第2種用漢字的 UNICODE 編碼範圍判 斷(漢字的 UNICODE 編碼範圍是4e00-9fbb),第3種用正則表達式判斷,下面是具體方法。正則表達式
可是實際上並不怎麼準確(從業務上講,好比全角輸入的數字),因此後來簡單修改了一下 代碼
ui
public static bool IsChinese( this string CString) { bool BoolValue = false; List<string> specialChar = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t" , "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T" , "U", "V", "W", "X", "Y", "Z", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "0", "'", "[", "]", "|", "\", """, ":", ";", ",", "。", "、", "?" }; for (int i = 0; i < CString.Length; i++) { if (Convert.ToInt32(Convert.ToChar(CString.Substring(i, 1))) < Convert.ToInt32(Convert.ToChar(128))) { BoolValue = false; } else { BoolValue = true; } } if (BoolValue) { if (specialChar.Any(x => CString.Contains(x))) { BoolValue = false; } } return BoolValue; }
固然還有一些特殊字符 也能經過,好比全角輸入的π,Ωthis
public static string String2Unicode(string source) { byte[] bytes = Encoding.Unicode.GetBytes(source); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < bytes.Length; i += 2) { stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0')); } return stringBuilder.ToString(); } public static string Unicode2String(string source) { return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace( source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16))); }