Encode a String Using Alternate Character Encoding - CSharp Language Basics

CSharp examples for Language Basics:string

Introduction

Character-Encoding Classes

Encoding Scheme Class Create Using
ASCIIASCIIEncoding GetEncoding(20127) or the ASCII property
Default Encoding GetEncoding(0) or the Default property
UTF-7UTF7Encoding GetEncoding(65000) or the UTF7 property
UTF-8UTF8Encoding GetEncoding(65001) or the UTF8 property
UTF-16 (big-endian) UnicodeEncoding GetEncoding(1201) or the BigEndianUnicode property
UTF-16 (little-endian) UnicodeEncoding GetEncoding(1200) or the Unicode property
Windows OS Encoding GetEncoding(1252)

Demo Code

using System;// ww w. j  a  v  a 2s .  c  o m
using System.IO;
using System.Text;
class MainClass
{
   public static void Main()
   {
      // Create a file to hold the output.
      using (StreamWriter output = new StreamWriter("output.txt"))
      {
         // Create and write a string containing the symbol for Pi.
         string srcString = "Area = \u03A0r^2 asdf!@#$%^&*()";
         output.WriteLine("Source Text : " + srcString);
         // Write the UTF-16 encoded bytes of the source string.
         byte[] utf16String = Encoding.Unicode.GetBytes(srcString);
         output.WriteLine("UTF-16 Bytes: {0}",BitConverter.ToString(utf16String));
         // Convert the UTF-16 encoded source string to UTF-8 and ASCII.
         byte[] utf8String = Encoding.UTF8.GetBytes(srcString);
         byte[] asciiString = Encoding.ASCII.GetBytes(srcString);
         // Write the UTF-8 and ASCII encoded byte arrays.
         output.WriteLine("UTF-8  Bytes: {0}",BitConverter.ToString(utf8String));
         output.WriteLine("ASCII  Bytes: {0}",BitConverter.ToString(asciiString));
         // Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded string and write.
         output.WriteLine("UTF-8  Text : {0}",Encoding.UTF8.GetString(utf8String));
         output.WriteLine("ASCII  Text : {0}",Encoding.ASCII.GetString(asciiString));
      }
   }
}

Related Tutorials