C# 如何解码字符串中的 Unicode 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9303257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:49:10  来源:igfitidea点击:

How to decode a Unicode character in a string

c#

提问by M_K

How do I decode this string 'Sch\u00f6nen' (@"Sch\u00f6nen") in C#, I've tried HttpUtility but it doesn't give me the results I need, which is "Sch?nen".

我如何@"Sch\u00f6nen"在 C# 中解码这个字符串 'Sch\u00f6nen' ( ),我试过 HttpUtility 但它没有给我我需要的结果,即“Sch?nen”。

采纳答案by M_K

Regex.Unescapedid the trick:

Regex.Unescape做到了:

System.Text.RegularExpressions.Regex.Unescape(@"Sch\u00f6nen");

Note that you need to be careful when testing your variants or writing unit tests: "Sch\u00f6nen"is already "Sch?nen". You need @in front of string to treat \u00f6as part of the string.

请注意,在测试变体或编写单元测试时需要小心:"Sch\u00f6nen"is already "Sch?nen"。您需要将@前面的字符串\u00f6视为字符串的一部分。

回答by findcaiyzh

If you landed on this question because you see "Sch\u00f6nen"(or similar \uXXXXvalues in string constant) - it is not encoding. It is a way to represent Unicode characters as escape sequence similar how string represents New Line by \nand Return by \r.

如果您因为看到"Sch\u00f6nen"(或\uXXXX字符串常量中的类似值)而遇到此问题- 它不是编码。这是一种将 Unicode 字符表示为转义序列的方法,类似于 string 表示 New Line by\n和 Return by 的方式\r

I don't think you have to decode.

我不认为你必须解码。

string unicodestring = "Sch\u00f6nen";
Console.WriteLine(unicodestring);

Sch?nen was outputted.

Sch?nen 被输出。