[Solved] Best way to sort a string of key value pairs


Given that I have a string of:


I would like:


What is the best practice in rust for sorting this (regex, sort_by, etc)? I would like to keep the string type when finished.


For sorting by keys, you might try a BTreeMap<key, value>, which is like a HashMap<key, value>, only sorted by keys. Of course, you’ll have to parse your string first, then populate the map, then deconstruct it back into a string.


Where did the string come from? There may be a better way to acquire the data, avoiding the problem of parsing a string containing structured data.

If not, you should be able to do something like split(,).map(trim).sort().

1 Like
fn sort(s: &str) -> String {
    let mut items: Vec<_> = s.split(",").map(|x| x.trim()).collect();

Minor addendum to others: this usecase seems amenable to sort_unstable rather than sort.

1 Like

Yes, I wanted to keep it simple so I used sort instead of sort_unstable, but that should also work.


Except when the key is > 10 ie Key10, Key1.

1 Like

Then use sort_by or sort_unstable_by and sort it how you want.

fn sort(s: &str) -> String {
    let mut items: Vec<_> = s.split(",").map(|x| x.trim()).collect();
    items.sort_by(|x, y| /* your comparator here */);

Here is a quick and dirty playground example. It punts entirely on error handling for the sake of brevity.

If your input string is quite long, then you may want to parse it into structured data upfront rather than (re)parsing for each comparison. Or, as @BatmanAoD mentioned, see if you can prep the data beforehand.

1 Like
Can this sorting code be rewritten in a more elegant way?

This all looks well and good but there seems to be no good way of dealing with key values > 10


I have tried to .parse but sort still expects comparing 2 str


Ahem, as you might have overlooked in @vitalyd’s playground example, it does allow more than 10 as the key number. In fact it allows alot more.


Apologies I wasn’t testing it correctly, thanks!


Thanks for all your help everybody. Was hoping I did not need the regex route!