0

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?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Veljko
  • 1,708
  • 12
  • 40
  • 80
  • 3
    "there are 12 different characters" - no, there's 7 - `\u0000` is _one character_. What are you doing with it that you need to treat it as through it has 12 characters? – D Stanley Feb 08 '16 at 18:31
  • Funny. Why do you think those are 12 characters? You are aware that 6 of them form one unicode character and are interpreted by the compiler? – TomTom Feb 08 '16 at 18:32
  • Are you looking for a way to have a string literal with its characters not interpreted as escape sequences? Because once you have a seven-character string, it's a seven character string; there's no unambiguous way to turn it into a 12-character string again. – Sergey Kalinichenko Feb 08 '16 at 18:42

2 Answers2

10

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.

Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
  • 1
    Beat me to it. The catch here is that `there will no longer be an actual unicode character in the string` if you use it escaped. – Brandon Feb 08 '16 at 18:32
4

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
Franz Wimmer
  • 1,477
  • 3
  • 20
  • 38