c#中的Unicode转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14560223/
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-10 12:15:31  来源:igfitidea点击:

Unicode Conversion in c#

c#unicode-string

提问by manoj

i am trying to assign Unicode on string but it return "Привет" string as "D??D?D2Dμ??" But i need "Привет", i am converting by following function .

我试图在字符串上分配 Unicode,但它返回“Привет”字符串为“D??D?D2Dμ??” 但我需要“Привет”,我正在通过以下功能进行转换。

public string Convert(string str)
{
    byte[] utf8Bytes = Encoding.UTF8.GetBytes(str);
    str = Encoding.UTF8.GetString(utf8Bytes);
    return str;
}

what can i do for solve this problem to return "Привет".

我该怎么做才能解决这个问题以返回“Привет”。

采纳答案by devio

Пis Unicode character 0x041F, and its UTF-8 encoding is 0xD0 0x9Fresulting in D?.

П是 Unicode 字符0x041F,其 UTF-8 编码0xD0 0x9F导致D?.

Since the function only returns the input parameter, as commenters already discussed, I conclude that your original input string is actually in UTF-8, and you want to convert it into native .Net string.

由于该函数只返回输入参数,正如评论者已经讨论过的,我得出结论,您的原始输入字符串实际上是 UTF-8,并且您希望将其转换为原生 .Net 字符串。

Where does the original string come from?

原始字符串来自哪里?

Instead of reading the input into a C# string, change your code to read a byte[], and then call Encoding.UTF8.GetString(inputUtf8ByteArray).

不要将输入读取到 C# 中string,而是将代码更改为读取byte[],然后调用Encoding.UTF8.GetString(inputUtf8ByteArray).

回答by Peter H

I Tried the following code below and these were my results:

我尝试了下面的代码,这些是我的结果:

        string test="Привет";
        byte[] utf8Bytes = Encoding.UTF8.GetBytes(test);

        String str1 = Encoding.Unicode.GetString(utf8Bytes);
        String str2 = Encoding.UTF8.GetString(utf8Bytes);

Output of str1=?胑???苑

str1=?胑???苑的输出

Output of str2=Привет

str2=Привет 的输出