Sort array of strings after criteria in the middle of each string

3 次查看(过去 30 天)
Hello community,
i have an array of strings of different lengths which i want to sort.
The arrray could look like this:
str = ["xer_cQwe" "po_bLo" "te_aUc"].
I want to sort the array in an alphabetical order regarding the criteria "_x". In each variable theres only one underline "_" and i want to sort it alphabetically for the then following letter.
Thanks in advance.
  2 个评论
langrg
langrg 2022-5-10
Hi,
There is certainly a better solution, but it should work:
str = ["xer_cQwe" "po_bLo" "te_aUc"];
match = regexp(str, '_\w+', 'match');
[~, idxSort] = sort([match{:}]);
strSorted = str(idxSort);
dpb
dpb 2022-5-10
编辑:dpb 2022-5-10
It's a pain can't return second argument from sort for such cases; I've asked it to be an enhancement that I think made the list to be considered, anyway. I built a local utility function that is a wrapper that does that for personal use.
Alternative also is the new(ish) pattern facility that lets one right search expressions w/o explicitly using regexp. It probably is no faster and may be slower...I've used it only a couple times so have to go research how to write something for given purpose.

请先登录,再进行评论。

采纳的回答

Voss
Voss 2022-5-10
str = ["xer_cQwe" "po_bLo" "te_aUc"];
[~,idx] = sort(extractAfter(lower(str),'_'));
sorted_str = str(idx)
sorted_str = 1×3 string array
"te_aUc" "po_bLo" "xer_cQwe"

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by