1. 程式人生 > >C#判斷字串是否為漢字

C#判斷字串是否為漢字

        /// <summary>
        /// 給定一個字串,判斷其是否只包含有漢字
        /// </summary>
        /// <param ></param>
        /// <returns></returns>
        public static bool IsChinese(string str)
        {
            Regex rx = new Regex("^[\u4e00-\u9fa5]$");
            for (int i = 0; i < str.Length; i++)
            {
                if (rx.IsMatch(str.Substring(i, 1)))
                {
                    continue;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 判斷一個word是否為GB2312編碼的漢字
        /// </summary>
        /// <param ></param>
        /// <returns></returns>
        private static bool IsGBCode(string word)
        {
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(word);
            if (bytes.Length <= 1) // if there is only one byte, it is ASCII code or other code
            {
                return false;
            }
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if (byte1 >= 176 && byte1 <= 247 && byte2 >= 160 && byte2 <= 254) //判斷是否是GB2312
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        /// <summary>
        /// 判斷一個word是否為GBK編碼的漢字
        /// </summary>
        /// <param ></param>
        /// <returns></returns>
        private static bool IsGBKCode(string word)
        {
            byte[] bytes = Encoding.GetEncoding("GBK").GetBytes(word.ToString());
            if (bytes.Length <= 1) // if there is only one byte, it is ASCII code
            {
                return false;
            }
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if (byte1 >= 129 && byte1 <= 254 && byte2 >= 64 && byte2 <= 254) //判斷是否是GBK編碼
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }