Kiven

Knowledge Has No Limit And Stick To It All The Time !
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

将汉字转为英文字母 整理笔记

Posted on 2011-11-08 10:29  KivenRo  阅读(3329)  评论(0编辑  收藏  举报

将汉字转为英文字母来记录数据,在此跟大家分享一下了。。。

       //调用 ConvertLetters(String chinese)方法,传入参数(只要是汉字,则转为大写的英文字母,可自己去定义了

        public String ConvertLetters(String chineseStr)
        {
            try
            {
                char[] buffer = new char[chinese.Length];
                for (int i = 0; i < chinese.Length; i++)
                {
                    buffer[i] = ConvertChar(chinese[i]);
                }
                return new String(buffer).Replace(" ", "");
            }
            catch
            {
                return "";
            }
        }
        
        public char ConvertChar(Char chinese)
        {
            try
            {
                Encoding gb2312 = Encoding.GetEncoding("GB2312");
                Encoding unicode = Encoding.Unicode;
                byte[] unicodeBytes = unicode.GetBytes(new Char[] { chinese });
                byte[] asciiBytes = Encoding.Convert(unicode, gb2312, unicodeBytes);
                if (asciiBytes.Length < 2)
                    return chinese; //待转换的字符在ascii码表示范围内
                int n = (int)asciiBytes[0] << 8;
                n += (int)asciiBytes[1];
                //   根据汉字区域码获取拼音声母  
                if (In(0xB0A1, 0xB0C4, n)) return 'A';
                if (In(0XB0C5, 0XB2C0, n)) return 'B';
                if (In(0xB2C1, 0xB4ED, n)) return 'C';
                if (In(0xB4EE, 0xB6E9, n)) return 'D';
                if (In(0xB6EA, 0xB7A1, n)) return 'E';
                if (In(0xB7A2, 0xB8c0, n)) return 'F';
                if (In(0xB8C1, 0xB9FD, n)) return 'G';
                if (In(0xB9FE, 0xBBF6, n)) return 'H';
                if (In(0xBBF7, 0xBFA5, n)) return 'J';
                if (In(0xBFA6, 0xC0AB, n)) return 'K';
                if (In(0xC0AC, 0xC2E7, n)) return 'L';
                if (In(0xC2E8, 0xC4C2, n)) return 'M';
                if (In(0xC4C3, 0xC5B5, n)) return 'N';
                if (In(0xC5B6, 0xC5BD, n)) return 'O';
                if (In(0xC5BE, 0xC6D9, n)) return 'P';
                if (In(0xC6DA, 0xC8BA, n)) return 'Q';
                if (In(0xC8BB, 0xC8F5, n)) return 'R';
                if (In(0xC8F6, 0xCBF0, n)) return 'S';
                if (In(0xCBFA, 0xCDD9, n)) return 'T';
                if (In(0xCDDA, 0xCEF3, n)) return 'W';
                if (In(0xCEF4, 0xD188, n)) return 'X';
                if (In(0xD1B9, 0xD4D0, n)) return 'Y';
                if (In(0xD4D1, 0xD7F9, n)) return 'Z';
                return ' ';
            }
            catch
            {
                return ' ';
            }
        }

        private bool In(int Lp, int Hp, int Value)
        {
            return ((Value <= Hp) && (Value >= Lp));
        }