C# 校驗字串是否漢字、其他字元,數字或字元

kevin_god發表於2009-09-08

C# 校驗字串是否漢字、其他字元,數字或字元

class Program
    {
     
        ///


        /// 控制檯測試
        ///

        ///
        static void Main(string[] args)
        {
            string str = null;
            string result = null;

            while (str != "x"){
                str = InputStr();
                result = CheckStr(str);
                Console.WriteLine("結果: {0}", result);
            }
        }

        ///


        /// 輸入漢字
        ///

        ///
        public static string InputStr()
        {
            string str;           

            Console.Write("請輸入: ");
            str = Console.ReadLine();         
            return str;            
        }

        ///


        ///  校驗字元是:漢字或其他字元, 數字或字元
        ///

        ///
        ///
        public static string CheckStr(string str)
        {
            string result = null;
            char c;

            if (IsChineseLetter(str, 0))
            {
                result = str + " = 漢字";
            }
            else
            {
                c = Convert.ToChar(str.Substring(0, 1));
                if (char.IsLetterOrDigit(c))
                {
                    result = str + " = 數字或字母";
                }
                else
                {
                    result = str + " = 特殊字元";
                }

            }
            return result;
        }


        ///


        /// 校驗是否漢字
        ///

        ///
        ///
        ///
        protected static bool IsChineseLetter(string input, int index)
        {
            int code = 0;
            int chfrom = Convert.ToInt32("4e00", 16);    //範圍(0x4e00~0x9fff)轉換成int(chfrom~chend)
            int chend = Convert.ToInt32("9fff", 16);
            if (input != "")
            {
                code = Char.ConvertToUtf32(input, index);    //獲得字串input中指定索引index處字元unicode編碼

                if (code >= chfrom && code <= chend)
                {
                    return true;     //當code在中文範圍內返回true

                }
                else
                {

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/17140602/viewspace-614164/,如需轉載,請註明出處,否則將追究法律責任。

相關文章