String.CompareTo() method ; Strange behavior

  • Thread starter Thread starter Kapil Sachdeva
  • Start date Start date
K

Kapil Sachdeva

Hi Guys:

Here is a snippet of code

char[] ch = new char[5];

ch[0] = 'A';
ch[1] = 'B'; // ch[2], ch[3], ch[4] are ' '

String _str = new String(ch);

int res = _str.CompareTo("AB");

If I run I get res == 0.
So does this mean that CompareTo method trims the whitespaces before and
after the string
which is to be compared ?

I am confused about this as the MSDN documentation about the function does
not say so.

Would be grateful if someone could validate my interpretation and incorrect
documentation

Regards & Thanks
Kapil
 
Kapil Sachdeva said:
Here is a snippet of code

char[] ch = new char[5];

ch[0] = 'A';
ch[1] = 'B'; // ch[2], ch[3], ch[4] are ' '

No, ch[2], ch[3] and ch[4] are '\0'. There's a big difference between a
space and a null character. If you compare "AB" and "AB " you get a
non-zero result.

In my experience, most of the time if you've got null characters in
your string, you've got a bug already.
String _str = new String(ch);

int res = _str.CompareTo("AB");

If I run I get res == 0.

So does this mean that CompareTo method trims the whitespaces before and
after the string which is to be compared ?

CompareTo performs a case-sensitive and culture-sensitive comparison.
It's at liberty to consider \0 to be a non-useful character in any
culture, I'd imagine. My guess is that it's using the IgnoreNonSpace
option - see CompareOptions for more details.
I am confused about this as the MSDN documentation about the function does
not say so.

Well, it *does* point you to CompareOptions and say it's sensitive to
the current culture...
 
Back
Top