Borrar filtros
Borrar filtros

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

3 visualizaciones (últimos 30 días)
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 comentarios
langrg
langrg el 10 de Mayo de 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 el 10 de Mayo de 2022
Editada: dpb el 10 de Mayo de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Voss
Voss el 10 de Mayo de 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"

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by