[英]C# String.Length from Microsoft Documentation
Microsoft documentation states that this code will return 7 characters Microsoft文档指出此代码将返回7个字符
The Length property returns the number of Char objects in this instance, not the number of Unicode characters.
Length属性返回此实例中Char对象的数量,而不是Unicode字符的数量。
string characters = "abc\u0000def";
Console.WriteLine(characters.Length); // Displays 7
I will need a function to return as result 12 because there are 12 different characters. 我将需要一个函数来返回结果12,因为有12个不同的字符。 Which function I may use?
我可以使用哪个功能?
You would have to prevent the interpretation of the literal by the compiler. 您将必须防止编译器对文字进行解释。 This can be done with the @ prefix, like this:
可以使用@前缀完成此操作,如下所示:
var characters = @"abc\u0000def";
The Length
property of this string will then return 12, but there will no longer be an actual unicode character in the string. 然后,该字符串的
Length
属性将返回12,但是字符串中将不再有实际的unicode字符。
The C# compiler will replace \
by a null byte. C#编译器将
\
替换为空字节。 That means, at execution time you will simply have only 7 characters in your memory. 这意味着,在执行时,您的内存中仅会包含7个字符。
If you don't want the compiler to replace the special char, you have to escape the backslash in the first place: 如果您不希望编译器替换特殊字符,则必须首先转义反斜杠:
string characters = "abc\\u0000def";
Console.WriteLine(characters.Length); // Displays 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.