在字符串中定义4字节UTF-16字符

Tho*_*ler 6 c# unicode encoding utf-16 character-encoding

我读过一个关于UTF-8,UTF-16和UCS-2的问题,几乎所有答案都说明UCS-2已经过时,C#使用UTF-16.

但是,我在C#中创建4字节字符U + 1D11E的所有尝试都失败了,所以我实际上认为C#仅使用UTF-16的UCS-2子集.

有我的尝试:

string s = "\u1D11E"; // gives the 2 character string "?E", because \u1D11 is ?
string s = (char) 0x1D11E; // won't compile because of an overflow
string s = Encoding.Unicode.GetString(new byte[] {0xD8, 0x34, 0xDD, 0x1E}); // gives ??
Run Code Online (Sandbox Code Playgroud)

C#字符串真的是UTF-16还是它们实际上是UCS-2?如果它们是UTF-16,我怎样才能将小提琴谱号放入我的C#弦中?

Han*_*ant 15

使用大写U代替:

  string s = "\U0001D11E";
Run Code Online (Sandbox Code Playgroud)

你忽略了大多数机器都是小端的:

  string t = Encoding.Unicode.GetString(new byte[] { 0x34, 0xD8, 0x1E, 0xDD });
Run Code Online (Sandbox Code Playgroud)


Jon*_*oni 5

C#绝对使用UTF-16.定义U + 0000 - U + FFFF范围之上的字符的正确方法是使用允许使用8个十六进制数字定义字符的转义序列:

string s = "\U0001D11E";
Run Code Online (Sandbox Code Playgroud)

如果你使用\u1D11E它被解释为U+1D11后跟一个字符E.

使用这些字符时要记住的一件事是String.Length属性和大多数字符串方法适用于UTF-16代码单元,而不是Unicode字符.从MSDN文档:

Length属性返回此实例中Char对象的数量,而不是Unicode字符数.原因是Unicode字符可能由多个Char表示.使用System.Globalization.StringInfo该类来处理每个Unicode字符而不是每个Char.