Convert a Unicode string to an escaped ASCII string

前端 未结 9 1518
广开言路
广开言路 2020-11-22 04:00

How can I convert this string:

This string contains the Unicode character Pi(π)

into an escaped A

9条回答
  •  無奈伤痛
    2020-11-22 04:44

    You need to use the Convert() method in the Encoding class:

    • Create an Encoding object that represents ASCII encoding
    • Create an Encoding object that represents Unicode encoding
    • Call Encoding.Convert() with the source encoding, the destination encoding, and the string to be encoded

    There is an example here:

    using System;
    using System.Text;
    
    namespace ConvertExample
    {
       class ConvertExampleClass
       {
          static void Main()
          {
             string unicodeString = "This string contains the unicode character Pi(\u03a0)";
    
             // Create two different encodings.
             Encoding ascii = Encoding.ASCII;
             Encoding unicode = Encoding.Unicode;
    
             // Convert the string into a byte[].
             byte[] unicodeBytes = unicode.GetBytes(unicodeString);
    
             // Perform the conversion from one encoding to the other.
             byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
    
             // Convert the new byte[] into a char[] and then into a string.
             // This is a slightly different approach to converting to illustrate
             // the use of GetCharCount/GetChars.
             char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
             ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
             string asciiString = new string(asciiChars);
    
             // Display the strings created before and after the conversion.
             Console.WriteLine("Original string: {0}", unicodeString);
             Console.WriteLine("Ascii converted string: {0}", asciiString);
          }
       }
    }
    

提交回复
热议问题