필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Pascal Viertel
Pascal Viertel 2022년 5월 10일
답변: Voss 2022년 5월 10일
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