Inserting spaces between the characters of two lines changes their order

I have two lines of the same length.
I assumed (possibly mistakenly) that inserting a space between each character of each line would not change their order.

var e1 = "12*4"; var e2 = "12-4"; Console.WriteLine(String.Compare(e1,e2)); // -1 (e1 < e2) var f1 = "1 2 * 4"; var f2 = "1 2 - 4"; Console.WriteLine(String.Compare(f1,f2)); // +1 (f1 > f2) 

If I insert other characters (e.g. x), the order is preserved.

What's happening?

Thanks in advance.

+5
source share
2 answers

If you use the Ordinal comparison, you will get the correct result.

The reason is that the comparison of ordinals is done by calculating the numerical value of each of the characters in the string object, so inserting spaces does not matter.

If you use other types of comparisons, there are other things. From the documentation:

An operation using word sorting rules performs a culture-sensitive comparison in which some nonalphanumeric Unicode characters may have special weights assigned to them. Using the rules for sorting words and conventions of a particular culture, a hyphen ("-") can have a very small weight assigned to it, next to the "cooperative" and "cooperative" of each other in a sorted list.

An operation using sorting ordinal orders performs a comparison based on the numeric value (Unicode code point) of each Char per line. The usual comparison is quick, but culture insensitive. when you use ordinal sorting rules to sort strings starting with Unicode characters (U +), the string U + xxxx precedes the string U + yyyy if xxxx is numerically less than yyyy.

+4
source

From MSDN:

The comparison uses the current culture to obtain culture information, such as casing rules and the alphabetical order of individual characters. For example, a culture may indicate that certain combinations of characters are treated as a single character, or upper and lower case characters are compared in a certain way, or that the sort order of a character depends on the characters that precede or follow it.

When comparing strings, you must call the Compare method (String, String, StringComparison), which requires that you explicitly specify the type of string comparison that this method uses.

This suggests that there is some cultural problem, which means that the last space changes the sort order of the two.

+2
source

Source: https://habr.com/ru/post/1270197/


All Articles