Sorting is not working correctly

£可爱£侵袭症+ 提交于 2019-12-24 10:17:59

问题


I am saving some files in document directory through my app using custom naming as "file1.format" ,"file2.format" and so on.Later I fetch these files in an Array and printing them in a loop then they are coming in sorted form but the problem arises when I store "file10.format" and so on. After this the result comes is some what unexpected. As after saving 10th file the output comes like

file1.foramt file10.format file2.format . . file6.format file61.format file7.format I don't know why sorting take all 1s or 2s on one place as shown above while it is expected that 10 should just comes after 9 not after 1.I used all kind of sorting but the result is coming same all time.


回答1:


If you want to sort file names "as the Finder does", use localizedStandardCompare. In particular, numbers in the strings are sorted according to their numeric value:

NSArray *files = [NSArray arrayWithObjects:@"file10.format", @"file2.format", @"file1.format", nil];
NSArray *sorted = [files sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
NSLog(@"%@", sorted);

Output:

2012-11-05 11:38:55.474 test77[533:403] (
    "file1.format",
    "file2.format",
    "file10.format"
)



回答2:


If you want to go with the regular string sorting sequence, then you should consider renaming your files. file00001.format, file00002.format and so on. In that case file00010.format follows file00009.format and file00011.format comes next




回答3:


It is actually working correctly.

file10.format

Comes before

file2.format 

because the character 0 is seen as less than the character . which it's being compared to (both characters are in the same place in their respective file names.

In fact, back in the day, before you young people with your fancy graphical operating systems, this is how the filesystem sorted files too. </old man rant>



来源:https://stackoverflow.com/questions/13229892/sorting-is-not-working-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!