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

#1

Given that I have a string of:

Key0=value,Key3=value,Key2=value,Key4=value,Key1=value

I would like:

Key0=value,Key1=value,....

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

#2

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.

2 Likes
#3

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
#4
fn sort(s: &str) -> String {
    let mut items: Vec<_> = s.split(",").map(|x| x.trim()).collect();
    items.sort();
    items.join(",")
}
4 Likes
#5

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

1 Like
#6

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

#7

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

1 Like
#8

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 */);
    items.join(",")
}
#9

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?
#10

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

#11

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

#12

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.

2 Likes
#13

Apologies I wasn’t testing it correctly, thanks!

#14

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