문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top