Strange string.Compare behaviour

R

RocketMan

If string.Compare("li", "l'") results to 1, I would assume
string.Compare("lio", "l'o") also results to 1, however it results to
-1.

It seems the single quote character is the only one causing this
behaviour, double quote and backquote characters compare as expected.
I've tried already specifying different CultureInfo's but without any
success.

The above behaviour causes sometimes problems with a binary search on
ordered data from an sql query.

Paul
 
K

Kevin Spencer

From the .Net SDK:

"The comparison terminates when an inequality is discovered or both strings
have been compared. However, if the two strings compare equal to the end of
one string, and the other string has characters remaining, then the string
with remaining characters is considered greater. The return value is the
result of the last comparison performed.

Unexpected results can occur when comparisons are affected by
culture-specific casing rules. For example, in Turkish, the following
example yields the wrong results because the file system in Turkish does not
use linguistic casing rules for the letter 'i' in "file"."

Basically, what this means is that, while the return value may be an
integer, it is only useful for you to know whether it is zero or non-zero.
If it is zero, the strings are exactly the same. Otherwise, they are
different.

Why do I say this? Because "the comparison terminates when an inequality is
discovered." That means that it will terminate on the first character it
finds that is not the same.

You can also compare strings using a character-by-character comparison.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Chicken Salad Alchemist

Big thicks are made up of lots of little thins.
 
R

RocketMan

Kevin,

Thanks for the info.

I am aware of this info but hoped that the InvariantCulture would
bypass any linguistic differences and the comparison would just end on
an inequality.

But based on your reply I digged a little deeper into the
documentation and came across the CompareInfo class. Together with the
CompareOptions enum I was able to get a more reliable result doing the
following:

int x =0;
CompareInfo compInfo = CompareInfo.GetCompareInfo("en-US");
x = compInfo.Compare("li", "l'", CompareOptions.StringSort);
x = compInfo.Compare("lio", "l'o", CompareOptions.StringSort);

The CompareOptions.StringSort was the magic key in this case!

Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top