问题
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