自然顺序文件名排序【含Matlab源码】

字母数字形式的文件名或文件路径,具有可自定义的数字格式。 字符串单元格数组的字母数字排序(1xN个字符)。考虑到字符串中出现的任何数字子字符串的值,对字符串进行排序。比较例如: >> A = {'a2.txt', 'a10.txt', 'a1.txt'};
>> sort(A)
ans = 'a1.txt' 'a10.txt' 'a2.txt'
>> natsortfiles(A)
ans = 'a1.txt' 'a2.txt' 'a10.txt' 

默认情况下,NATSORTFILES将所有连续的数字解释为整数,可以使用正则表达式指定数字子串识别:有关详细信息,请参见NATSORT。

NATSORTFILES不会执行幼稚的自然顺序排序,而是对文件名和文件扩展名分别进行排序,以确保字典排序,其中较短的文件名总是排在长文件名之前。同样,在每个文件分隔符处拆分文件路径,并分别对文件层次结构的每个级别进行排序。

### DIR和单元阵列的示例###

D = 'C:\Test';
S = dir(fullfile(D,'*.txt'));
N = natsortfiles({S.name});
for k = 1:numel(N)
fullfile(D,N{k})
end

###文件依赖性###

自然顺序排序由功能NATSORT(文件交换34464)提供。NATSORTFILES支持所有NATSORT的可选输入。

### Examples ###

>> B = {'test_new.m'; 'test-old.m'; 'test.m'};
>> sort(B) % Note '-' sorts before '.':
ans =
'test-old.m'
'test.m'
'test_new.m'
>> natsortfiles(B) % Shorter names before longer (dictionary sort):
ans =
'test.m'
'test-old.m'
'test_new.m'

>> C = {'test2.m'; 'test10-old.m'; 'test.m'; 'test10.m'; 'test1.m'};
>> sort(C) % Wrong numeric order:
ans =
'test.m'
'test1.m'
'test10-old.m'
'test10.m'
'test2.m'
>> natsortfiles(C) % Shorter names before longer:
ans =
'test.m'
'test1.m'
'test2.m'
'test10.m'
'test10-old.m'

%% Directory Names:
>> D = {'A2-old\test.m';'A10\test.m';'A2\test.m';'A1archive.zip';'A1\test.m'};
>> sort(D) % Wrong numeric order, and '-' sorts before '\':
ans =
'A10\test.m'
'A1\test.m'
'A1archive.zip'
'A2-old\test.m'
'A2\test.m'
>> natsortfiles(D) % Shorter names before longer (dictionary sort):
ans =
'A1archive.zip'
'A1\test.m'
'A2\test.m'
'A2-old\test.m'
'A10\test.m'

完整资料领取请阅读全文

未经允许不得转载!自然顺序文件名排序【含Matlab源码】