Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort a vector of strings by char in Rust?

What is the more idiomatic way to sort a vector of strings by char?
Example:

Input:
["3r", "2n", "2s", "7r", "1s", "1s", "6r", "1s", "1n", "1n", "5n", "9n", "3r"]
Desired output:
["1n", "1n", "2n", "5n", "9n, "3r", "3r", "6r", "7r", "1s", "1s", "1s", "2s"]

First they need to be sorted on the second char so they are grouped together, after that sorted by first char.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried a bunch of things with .filter and .sort_by but was not successful.

>Solution :

If your strings are always two characters long, and you always want to sort them by the second character first, you can use .sort_by with a comparator which looks at the strings in reverse:

let mut input = vec!("3r", "2n", "2s", "7r", "1s", "1s", "6r", "1s", "1n", "1n", "5n", "9n", "3r");
input.sort_by(|a, b| a.chars().rev().cmp(b.chars().rev()));
let expected = vec!("1n", "1n", "2n", "5n", "9n", "3r", "3r", "6r", "7r", "1s", "1s", "1s", "2s");
assert!(input == expected);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading