排序包含数字的字符串以用户友好的方式字符串、友好、方式、数字

2023-09-11 01:52:19 作者:绝版型、少年

被用来分选字符串的标准方式,我很惊讶,当我发现的Windows中的一种先进的方式用他们的名字排序文件。我给大家举一个例子:

Being used to the standard way of sorting strings, I was surprised when I noticed that Windows sorts files by their names in a kind of advanced way. Let me give you an example:

Track1.mp3 Track2.mp3 Track10.mp3 Track20.mp3

Track1.mp3 Track2.mp3 Track10.mp3 Track20.mp3

我认为,根据字母和数字由单独的名称的比较(在排序)。

I think that those names are compared (during sorting) based on letters and by numbers separately.

在另一方面,下面是同一列表排序以标准方式如下: Track1.mp3 Track10.mp3 Track2.mp3 Track20.mp3

On the other hand, the following is the same list sorted in a standard way: Track1.mp3 Track10.mp3 Track2.mp3 Track20.mp3

我想创建一个比较算法FFT德尔福,将让我排序,以同样的方式串。起初我以为这将是足够的,比较连续字符两个字符串,而他们的信件。当一个数字将在两个串的一些位置可以发现,我将读取所有的数字跟随它们,以形成一个数字,然后比较这些数字

I would like to create a comparing alogorithm in Delphi that would let me sort strings in the same way. At first I thought it would be enough to compare consecutive characters of two strings while they are letters. When a digit would be found at some position of both the strings, I would read all digits following them to form a number and then compare the numbers.

要举一个例子,我将比较第10首和TRACK2字符串是这样的: 1)读取字符,而他们是平等的,而他们的信件:跟踪,跟踪 2)如果发现一个数字,阅读下面的数字:10,2 2A),如果他们是平等的,去1要不然完成 十大于二,所以10首大于TRACK2

To give you an example, I'll compare "Track10" and "Track2" strings this way: 1) read characters while they are equal and while they are letters: "Track", "Track" 2) if a digit is found, read all following digits: "10", "2" 2a) if they are equal, go to 1 or else finish Ten is greater than two, so "Track10" is greater than "Track2"

这已似乎一切都会好起来的,直到我发现,在我的测试中,该Windows视为Track010低于10首,而我认为第一个是更大,因为它是更长的(不是按提我的算法这两个字符串是相等的,这是错误的)。

It had seemed that everything would be all right until I noticed, during my tests, that Windows considered "Track010" lower than "Track10", while I thought the first one was greater as it was longer (not mentioning that according to my algorithm both the strings would be equal, which is wrong).

你能提供给我的想法究竟是如何的Windows按名称排序文件,或者你有一个随时可以使用的算法(在任何编程语言),我可以立足?

Could you provide me with the idea how exactly Windows sorts files by names or maybe you have a ready-to-use algorithm (in any programming language) that I could base on?

非常感谢! 马里乌什

Thanks a lot! Mariusz

推荐答案

杰夫写了这个文章的编码恐怖。这就是所谓的自然排序,在那里你有效治疗组数字作为一个单一的性格。有实现在外面的阳光下每一种语言,但奇怪的是它不是通常内置在大多数语言标准库。

Jeff wrote up an article about this on Coding Horror. This is called natural sorting, where you effectively treat a group of digits as a single "character". There are implementations out there in every language under the sun, but strangely it's not usually built-in to most languages' standard libraries.