C# unicode string 转换 codepoint

C# 的string和StringBuilder都支持使用codepoint直接构造字符串。unicode的字符串形式一般都是’\u1234’这种转义模式。 其中‘1234’就是unicode codepoint的16进制形式。

通过计算,可以把这种形式的字符串,直接转化为int32类型的codepoint。


        /// <summary>
        /// Get the unicode code point
        /// </summary>
        private static int GetUnicodeCodePoint(char c1, char c2, char c3, char c4)
        {

            return UnicodeCharToInt(c1) * 0x1000 +
                   UnicodeCharToInt(c2) * 0x100  +
                   UnicodeCharToInt(c3) * 0x10   +
                   UnicodeCharToInt(c4);
        }


        /// <summary>
        /// Single unicode char convert to int
        /// </summary>
        private static int UnicodeCharToInt(char c)
        {
            switch (c)
            {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    return c - '0';

                case 'a':
                case 'b':
                case 'c':
                case 'd':
                case 'e':
                case 'f':
                    return c - 'a' + 10;

                case 'A':
                case 'B':
                case 'C':
                case 'D':
                case 'E':
                case 'F':
                    return c - 'A' + 10;
            }

            throw new Exception(string.Format("Unicode char '{0}' error", c));
        }

使用的时候codepoint需要强转为char类型。比如:

StringBuilder sb = new StringBuilder();
sb.Append((char) GetUnicodeCodePoint(c1, c2, c3, c4));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章