Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the capital letter is greater than small letter in .Net?

Tags:

java

c#

compare

In Java:

"A".compareTo("a"); return -32 //"A" is less than "a".

In .Net, use String.CompareTo:

"A".CompareTo("a"); return 1 //"A" is greater than "a".

In .Net, use Char.CompareTo:

'A'.CompareTo('a'); return -32 //"A" is less than "a".

I know the Java compares string characters using its position in unicode table, but .Net is not. How determines which capital letter is greater than small letter in .Net?

String.CompareTo Method (String)

like image 359
smartleos Avatar asked Jun 28 '13 06:06

smartleos


2 Answers

The doc I could find says that:

This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture.

So, it is not quite the same as Java's .compareTo() which does a lexicographical comparison by default, using Unicode code points, as you say.

Therefore, in .NET, it depends on your current "culture" (Java would call this a "locale", I guess).

It seems that if you want to do String comparison "à la Java" in .NET, you must use String.CompareOrdinal() instead.

On the opposite, if you want to do locale-dependent string comparison in Java, you need to use a Collator.

Lastly, another link on MSDN shows the influence of cultures on comparisons and even string equality.

like image 163
fge Avatar answered Sep 28 '22 06:09

fge


From Java String

Returns: the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

From .Net String.CompareTo

This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

This post explains the difference between the comparison types

And the doc explains the difference between all the comparison types;

IF you look at these two, CurrentCulture and Ordinal

 StringComparison.Ordinal: 
 LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131) 
 LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049) 
 LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U

 StringComparison.CurrentCulture: 
 LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131) 
 LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049) 
 LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049) 

Ordinal is the only one where "i" > "I" and hence Java like

like image 21
Java Devil Avatar answered Sep 28 '22 08:09

Java Devil