Effacer les filtres
Effacer les filtres

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

3 vues (au cours des 30 derniers jours)
Pascal Viertel
Pascal Viertel le 10 Mai 2022
Réponse apportée : Voss le 10 Mai 2022
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 commentaires
langrg
langrg le 10 Mai 2022
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 le 10 Mai 2022
Modifié(e) : dpb le 10 Mai 2022
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.

Connectez-vous pour commenter.

Réponse acceptée

Voss
Voss le 10 Mai 2022
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"

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by