判斷一個字符是不是漢字通常有三種方法,第一種用 ASCII 碼判斷,第二種用漢字的 UNICODE 編碼範圍判 斷,第三種用正則表達式判斷,以下是具體方法。
1、用ASCII碼判斷
在 ASCII碼錶中,英文的範圍是0-127,而漢字則是大於127,具體代碼如下:
1 string text = "是不是漢字,ABC,柯樂義"; 2 for (int i = 0; i < text.Length; i++) 3 { 4 if ((int)text[i] > 127) 5 Console.WriteLine("是漢字"); 6 else 7 Console.WriteLine("不是漢字"); 8 }
2、用漢字的 UNICODE 編碼範圍判斷
漢字的 UNICODE 編碼範圍是4e00-9fbb,具體代碼如下:
1 string text = "是不是漢字,ABC,keleyi.com"; 2 char[] c = text.ToCharArray(); 3 4 for (int i = 0; i < c.Length;i++) 5 if (c[i] >= 0x4e00 && c[i] <= 0x9fbb) 6 Console.WriteLine("是漢字"); 7 else 8 Console.WriteLine("不是漢字");
3、用正則表達式判斷
用正則表達式判斷也是用漢字的 UNICODE 編碼範圍,具體代碼如下:
1 string text = "是不是漢字,ABC,keleyi.com"; 2 for (int i = 0; i < text.Length; i++) 3 { 4 if (Regex.IsMatch(text[i].ToString(), @"[\u4e00-\u9fbb]+{1}quot;)) 5 Console.WriteLine("是漢字"); 6 else 7 Console.WriteLine("不是漢字"); 8 }