Idiomatic String Manipulation

I've been working with Strings lately and am curious if there's a better/more Rust way to do what I've come up with. The idea is to take a string, remove all the whitespace, convert it to lowercase and then sort it. From what I've seen almost all sorting examples involve sorting Vecs and not Strings. This is what I came up with so far.

fn clean_string(string: &str) -> String {
    let mut chars = string.split_whitespace()
        .collect::<Vec<_>>()
        .join("")
        .to_lowercase()
        .chars()
        .collect::<Vec<_>>();
    chars.sort();

    chars.iter()
        .collect()
}

Is there a better way to do this without having to convert and collect over and over? Something similar to this?

string.split_whitespace()
    .join("")
    .to_lowercase()
    .sort()

That creates temporary strings unnecessarily.

s.chars().filter(|c| !c.is_whitespace()).map(|c| c.to_lowercase()).collect()

does it in one go.

You could have a fast path for ASCII-only strings, which can be sorted as Vec<u8>.

4 Likes

That is way better then what I came up with. I like how clean that is. Thanks for the quick example.