我将以下 C# 代码编译为 Sort.exe:
using System;
using System.Collections.Generic;
class Test
{
public static int Main(string[] args)
{
string text = null;
List<string> lines = new List<string>();
while((text = Console.In.ReadLine()) != null)
{
lines.Add(text);
}
lines.Sort();
foreach(var line in lines)
Console.WriteLine(line);
return 0;
}
}
我有一个文件 input.txt,它的内容有以下 5 行:
x000000000000000000093.000000000
x000000000000000000037.000000000
x000000000000000100000.000000000
x000000000000000000538.000000000
x-00000000000000000020.000000000
现在,如果我在命令提示符下运行它,输出如下:
C:\Users\girijesh\AppData\Local\Temp>sort < input.txt
x000000000000000000037.000000000
x000000000000000000093.000000000
x-00000000000000000020.000000000
x000000000000000000538.000000000
x000000000000000100000.000000000
我无法理解以 x-
开头的字符串(输出中的第 3 行)出现在以 x0
开头的字符串中间的字符串排序方式.第三行应该在顶部或底部。 Excel 也表现出相同的行为。
最佳答案
在许多文化(包括不变文化)中,连字符是一个对于排序目的来说不太重要的字符。在大多数文本中,这是有道理的:pre-whatever
和 pre-whatever
非常相似。比如下面的列表是这样排序的,我觉得这样很好:
preasdf
prewhatever
pre-whatever
prezxcv
你似乎想要一个 Ordinal
比较,其中值纯粹通过其 unicode 代码点值进行比较。如果您将行更改为:
lines.Sort(StringComparer.Ordinal);
那么你的结果是:
x-00000000000000000020.000000000
x000000000000000000037.000000000
x000000000000000000093.000000000
x000000000000000000538.000000000
x000000000000000100000.000000000
如果您想知道为什么 -...20.0
值会出现在原来的位置,请考虑如果您删除 -
(和与上面的 pre
列表进行比较)。
x000000000000000000037.000000000
x000000000000000000093.000000000
x00000000000000000020.000000000
x000000000000000000538.000000000
x000000000000000100000.000000000
如果您的输入始终采用 x[some number]
格式,我会将 x
之后的值解析为 decimal
或double
,然后对其进行排序。这将使确保预期行为变得更容易,并且总体上更好。
关于c# - 字符串排序陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23655794/