以用户友好的方式对包含数字的字符串进行排序 [英] Sorting strings containing numbers in a user friendly way

查看:26
本文介绍了以用户友好的方式对包含数字的字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

习惯了标准的字符串排序方式,当我注意到 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.

另一方面,以下是以标准方式排序的相同列表:
音轨1.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

我想在 Delphi 中创建一个比较算法,让我以相同的方式对字符串进行排序.起初,我认为将两个字符串的连续字符进行比较就足够了,而它们是字母.当在两个字符串的某个位置找到一个数字时,我会读取它们后面的所有数字以形成一个数字,然后比较这些数字.

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.

举个例子,我将这样比较Track10"和Track2"字符串:
1) 读取相等且为字母的字符:Track"、Track"
2)如果找到一个数字,读取以下所有数字:10",2"
2a) 如果它们相等,则转到 1 否则完成
十大于二,所以Track10"大于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"低于Track10",而我认为第一个更大,因为它更长(没有提到根据我的算法两个字符串都相等,这是错误的).

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 在 Coding Horror 上写了一篇关于此的文章.这称为自然排序,您可以在其中有效地对待一个群体数字作为单个字符".太阳底下的每种语言都有实现,但奇怪的是它通常没有内置到大多数语言的标准库中.

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.

这篇关于以用户友好的方式对包含数字的字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆