在c#中从string转换为us-ascii

kor*_*ead 1 c# encoding ascii

我想将像"123"这样的字符串转换为像"\ u0031\u0032\u0033"这样的字符串.我怎么能在.NET中这样做?例如:反向转换:

Encoding enc = Encoding.GetEncoding("us-ascii",
                                          new EncoderExceptionFallback(),
                                          new DecoderExceptionFallback());
            byte[] by = enc.GetBytes(s);
            string ans = enc.GetString(by);
            return ans;
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

.NET中的字符串已经是Unicode,因此不需要将它们从Unicode转换为Unicode.

如果要输出unicode转义字符串,请尝试以下操作:

string ans = string.Concat(s.Select(c => string.Format("\\u{0:x4}", (int)c)).ToArray());
Run Code Online (Sandbox Code Playgroud)

结果:

\u0031\u0032\u0033
Run Code Online (Sandbox Code Playgroud)

看到它在线工作:ideone

在.NET 4.0中,您可以省略对它的调用ToArray.