Unicode轉換成漢字的C#解碼代碼


rt 根據所具有的Unicode編碼用C#語言把它轉換成漢字的代碼

師傅的代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static string UnicodeToGB( string text)
         {
             System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})" );
             if (mc != null && mc.Count > 0)
             {
                 foreach (System.Text.RegularExpressions.Match m2 in mc)
                 {
                     string v = m2.Value;
                     string word = v.Substring(2);
                     byte [] codes = new byte [2];
                     int code = Convert.ToInt32(word.Substring(0, 2), 16);
                     int code2 = Convert.ToInt32(word.Substring(2), 16);
                     codes[0] = ( byte )code2;
                     codes[1] = ( byte )code;
                     text = text.Replace(v, Encoding.Unicode.GetString(codes));
                 }
             }
             else
             {
 
             }
             return text;
         }

  這是以foreach來處理每個正則表達式的值並且連接起來代碼

 

我根據師傅的代碼修改的代碼,雖然簡短了點但是運用的確實for循環

1
2
3
4
5
6
7
8
9
10
11
12
public static string unicodetogb( string text)
{
     System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})" );
     string a = text.Replace( "\\u" , "" );
     char [] arr = new char [mc.Count];
     for ( int i = 0; i < arr.Length; i++)
     {
         arr[i] = ( char )Convert.ToInt32(a.Substring(i * 4, 4), 16);
     }
     string c = new string (arr);
     return c;
}

  其中 mc是通過以迭代方式將正則表達式模式應用於輸入字符串所找到的成功匹配的集合,它具有count屬性。我是把整個Unicode代碼轉換成沒有\u的字符串然后對其進行處理的方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM