Microsoft文档中的C#String.Length

时间:2016-02-08 18:25:50

标签: c# string string-length

Microsoft documentation states此代码将返回7个字符

  

Length属性返回此实例中Char对象的数量,       不是Unicode字符的数量。

string characters = "abc\u0000def";
Console.WriteLine(characters.Length);    // Displays 7

我需要一个函数来返回结果12因为有12个不同的字符。我可以使用哪种功能?

2 个答案:

答案 0 :(得分:10)

您必须阻止编译器对文字的解释。这可以使用@前缀完成,如下所示:

var characters = @"abc\u0000def";

此字符串的Length属性将返回12,但字符串中将不再存在实际的unicode字符。

答案 1 :(得分:4)

C#编译器将用空字节替换\u0000。这意味着,在执行时,您的内存中只有7个字符。

如果您不希望编译器替换特殊字符,则必须首先转义反斜杠:

string characters = "abc\\u0000def";
Console.WriteLine(characters.Length);    // Displays 12
相关问题