Convert a Unicode string to an escaped ASCII string

前端 未结 9 1403
广开言路
广开言路 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:47

    class Program
    {
            static void Main(string[] args)
            {
                char[] originalString = "This string contains the unicode character Pi(π)".ToCharArray();
                StringBuilder asAscii = new StringBuilder(); // store final ascii string and Unicode points
                foreach (char c in originalString)
                {
                    // test if char is ascii, otherwise convert to Unicode Code Point
                    int cint = Convert.ToInt32(c);
                    if (cint <= 127 && cint >= 0)
                        asAscii.Append(c);
                    else
                        asAscii.Append(String.Format("\\u{0:x4} ", cint).Trim());
                }
                Console.WriteLine("Final string: {0}", asAscii);
                Console.ReadKey();
            }
    }
    

    All non-ASCII chars are converted to their Unicode Code Point representation and appended to the final string.

提交回复
热议问题