1

我正在使用 C#、.NET 3.5。我有以下代码

string.Compare("KHA","KTB",true)

它返回值 1。这意味着 KHA > KTB 按字母顺序排列。我希望它返回值-1。

谁能帮我解决这个问题?

是的,你们都是对的。这是因为文化。我添加 CultureInfo.InvariantCulture 并解决了。谢谢大家!

4

3 回答 3

2

srig.Compare返回排序顺序中的相对位置由于'H'出现在'T'之前,这就是你得到的原因1

它应该返回-1,查看图片 在此处输入图像描述

您的编译器一定有问题,它应该返回-1并且您对它的理解string.Compare是正确的。

您可以尝试使用CultureInfo.InvariantCulture

int value = string.Compare("KHA", "KTB", true,CultureInfo.InvariantCulture);
于 2012-08-07T03:29:06.270 回答
1

The call string.Compare("KHA","KTB",true) should return -1 as expected. It does when I test it.

If you get any other result, you either are using other strings, or you have a default culture where 'T' is actually considered to come before 'H'.

For the latter case, you can specify a culture info in the call:

string.Compare("KHA", "KHB", true, CultureInfo.InvariantCulture)
于 2012-08-07T03:34:04.637 回答
1

If you are really getting 1 against string.Compare("KHA","KTB",true) then your system's current culture must be making an effect. Check the documentation of String.Compare. Also check the best practices of comparing a string here.

于 2012-08-07T03:34:34.710 回答