Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "K".Length gives me wrong result?

I am seeing this strange issue, and can't find anything similar to this anywhere on the web:

int l = "K".Length;    //This actually returns 2 !!! The 'Autos' window in
                       //the debugger also shows "K".Length as 2.

string s = "K";
l = s.Length;          //Whereas this returns 1 as expected

I tried this in various C# projects and even asked another developer to confirm the behaviour is identical in a different project on a different machine.

I tried the same in VB.NET:

Dim l As Integer = "K".Length    'This returns 1 correctly

Am I loosing it?

like image 638
Christian Avatar asked Mar 20 '13 11:03

Christian


2 Answers

That's because "K", unlike "K", has an invisible character in it, namely an ascii value of 30 (record separator).

You can verify this by doing

byte[] bytes = Encoding.ASCII.GetBytes("K");
like image 56
harold Avatar answered Sep 18 '22 18:09

harold


Your "K" actually contains two characters. One "K" and the other unicode invisible symbol. When I type clearly "-K-" it shows 1, when I copy-paste your code, it is 2. Paste it twice and it will be 4.

like image 43
AgentFire Avatar answered Sep 20 '22 18:09

AgentFire