Question

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?

Était-ce utile?

La solution

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");

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top