Veljko
Veljko

Reputation: 1808

C# String.Length from Microsoft Documentation

Microsoft documentation states that this code will return 7 characters

The Length property returns the number of Char objects in this instance, not the number of Unicode characters.

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. Which function I may use?

Upvotes: 0

Views: 460

Answers (2)

Cee McSharpface
Cee McSharpface

Reputation: 8735

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.

Upvotes: 10

Franz Wimmer
Franz Wimmer

Reputation: 1487

The C# compiler will replace \u0000 by a null byte. That means, at execution time you will simply have only 7 characters in your memory.

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

Upvotes: 4

Related Questions