当前位置:首页 > 网络编程 > 软件语言 > .NET > C#将字符串从一种编码转换为另一种编码

C#将字符串从一种编码转换为另一种编码

点击次数:93 次 发布日期:2008-11-06 07:54:37 作者:源代码网
源代码网推荐
广告载入中
1. using System;
   2. using System.Text;
   3. 
   4. namespace ConvertExample
   5. {
   6.    class ConvertExampleClass
   7.    {
   8.       static void Main()
   9.       {
  10.          string unicodeString = "This string contains the unicode character Pi(u03a0)";
  11. 
  12.          // Create two different encodings.
  13.          Encoding ascii = Encoding.ASCII;
  14.          Encoding unicode = Encoding.Unicode;
  15. 
  16.          // Convert the string into a byte[].
  17.          byte[] unicodeBytes = unicode.GetBytes(unicodeString);
  18. 
  19.          // Perform the conversion from one encoding to the other.
  20.          byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
  21. 
  22.          // Convert the new byte[] into a char[] and then into a string.
  23.          // This is a slightly different approach to converting to illustrate
  24.          // the use of GetCharCount/GetChars.
  25.          char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
  26.          ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
  27.          string asciiString = new string(asciiChars);

  28. 
  29.          // Display the strings created before and after the conversion.
  30.          Console.WriteLine("Original string: {0}", unicodeString);
  31.          Console.WriteLine("Ascii converted string: {0}", asciiString);
  32.       }
  33.    }
  34. }

源代码网推荐

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华