Change escaped unicode to string in C# [duplicate]

最后都变了- 提交于 2021-02-08 04:00:11

问题


In c# I have

string x = @"\u0044\u0068\uD83D\uDE07\u90FD\u5728"

I need to turn it into:

Dh😇都在

How do I do that? Specifically, how do I know when \uD83D\uDE07 is one character as compared to two?


回答1:


You might have to parse each char representation into an int and then convert to a char:

string x = @"\u0044\u0068\uD83D\uDE07\u90FD\u5728";
var chars = x.Split(new[]{@"\u"}, StringSplitOptions.RemoveEmptyEntries)
    .Select(c => (char)Convert.ToInt32(c, 16))
    .ToArray();
var output = new string(chars);
// output = Dh😇都在



回答2:


I know newtonsoft json.net will convert, so I would use that if was one of my projects and I already had references to it:

using Newtonsoft.Json;

var output = new JsonTextReader(new StringReader($"\"{x}\"")).ReadAsString();

//output = Dh😇都在

Advantages are it's going to cope with nonunicode characters as well, I.e. "Z\u0044" -> "ZD". Disadvantage is that in it's current state there are nonunicode characters it won't cope with, such as quote obviously: "A\"B" will fail.



来源:https://stackoverflow.com/questions/35026517/change-escaped-unicode-to-string-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!