C#.NET GB2312编码转化为中文

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace GB2312ConvertChinese
{
    class Program
    {
        static void Main(string[] args)
        {
            string content = "/HTC Butterfly X920e是刚刚推出不久的一款智能手机,该机的5.0英寸大屏&";
            Console.WriteLine(GBKToChinese(content));
            Console.ReadKey();
        }
        static string GBKToChinese(string content)
        {
            string pattern = "&#(.+?);";          
            if (!Regex.IsMatch(content, pattern))
                return content;
            MatchCollection collection = Regex.Matches(content, pattern);
            foreach (Match item in collection)
            {
                string GBK_Code = item.Value;
                string GBK_Value = item.Groups[1].Value;
                string chinese = ((char)Convert.ToInt32(GBK_Value, 10)).ToString();
                content = content.Replace(GBK_Code, chinese);
            }
            return content;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        //获得GB2312编码。
        static void Main(string[] args)
        {
            string str = "研究中心";
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
                sb.AppendFormat("&#{0};", Convert.ToString((int)c, 10));
            Console.WriteLine(sb.ToString());
            Console.ReadKey();
        }
    }
}


 

参考:请问关于\u开头的汉字编码是什么类型的编码,c#怎样转换

URL:http://www.phpfans.net/ask/MTcyNzYzNw.html 

unicode字符
如果是这样的string str = "\u5317\u4eac";
那直接输出就可以了
如果这个字符串是从其它地方得到的话,就这样:

C# code
    
    
    
    
string str = " \\u5317\\u4eac " ; string [] temp = str.Split( new string [] { " \\u " }, StringSplitOptions.RemoveEmptyEntries); for ( int i = 0 ; i < temp.Length; i ++ ) temp[i] = (( char )Convert.ToInt32(temp[i], 16 )).ToString(); string result = string .Join( "" , temp); Console.WriteLine(result);

 

要从汉字转成unicode编码:

C# code
    
    
    
    
string str = " 北京 " ; StringBuilder sb = new StringBuilder(); foreach ( char c in str) sb.AppendFormat( " \\u{0} " , Convert.ToString(( int )c, 16 )); Response.Write(sb.ToString());

 

 

你可能感兴趣的:(C#.NET GB2312编码转化为中文)