[Tips] How to encode and decode unicode escape C# character

0
32

What’s unicode escape C# character?
That same as below character.

How to encode and decode unicode escape C# character
"ud83cudf1f[Cu1eadp Nhu1eadt"

You’ll always meet this character when you dump or get data from website. The data send from server to web through JSON file

“Convert a Unicode string to an escaped ASCII string”

This tips will help you Encode and Decode unicode escape C# character! Follow my source code, you can easy do it!

// unicode escape C#
string unicodeString = "ud83cudf1f[Cu1eadp Nhu1eadt";

Console.WriteLine(unicodeString);

Console.WriteLine(" -------------------------------------------- ");
string encoded = EncodeNonAsciiCharacters(unicodeString);
Console.WriteLine(encoded);

Console.WriteLine(" -------------------------------------------- ");
string decoded = DecodeEncodedNonAsciiCharacters(encoded);
Console.WriteLine(decoded);



static string EncodeNonAsciiCharacters(string value)
{
StringBuilder sb = new StringBuilder();
    foreach (char c in value)
    {
    if (c > 127)
        {
        // This character is too big for ASCII
            string encodedValue = "\u" + ((int)c).ToString("x4");
            sb.Append(encodedValue);
        }
        else
        {
            sb.Append(c);
        }
    }
    return sb.ToString();
}

static string DecodeEncodedNonAsciiCharacters(string value)
{
return Regex.Replace(
    value,
           @"\u(?<Value>[a-zA-Z0-9]{4})",
           m =>
           {
return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString();
           });
}

Leave your comment if you have any feedback or questions about encode and decode unicode escape C# character

Zidane