根据第一个字符对字符串进行排序 [英] sort string according to first characters matlab
本文介绍了根据第一个字符对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由几个字符串组成的单元格数组
I have an cell array composed by several strings
names = {'2name_19surn', '3name_2surn', '1name_2surn', '10name_1surn'}
,我想根据前缀编号对它们进行排序.
and I would like to sort them according to the prefixnumber.
我尝试过
[~,index] = sortrows(names.');
sorted_names = names(index);
但我知道
sorted_names = {'10name_1surn', '1name_2surn', '2name_19surn', '3name_2surn'}
而不是期望的
sorted_names = {'1name_2surn', '2name_19surn', '3name_2surn','10name_1surn'}
有什么建议吗?
推荐答案
使用正则表达式的简单方法:
Simple approach using regular expressions:
r = regexp(names,'^\d+','match'); %// get prefixes
[~, ind] = sort(cellfun(@(c) str2num(c{1}), r)); %// convert to numbers and sort
sorted_names = names(ind); %// use index to build result
这篇关于根据第一个字符对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文