How can I sort the characters of a string in Rust?
10,689
Solution 1
I did this and got the desired output. However this may not be the best way.
use std::iter::Iterator;
use std::iter::FromIterator;
fn main() {
let wordy: String = "I am a hello world example".to_owned();
let s_slice: &str = &wordy[..];
let mut chars: Vec<char> = s_slice.chars().collect();
chars.sort_by(|a, b| b.cmp(a));
println!("test{:?}", chars);
let s = String::from_iter(chars);
println!("{}", s);
}
Solution 2
If you're okay with using crates, you can use the itertools
crate to simplify things quite a bit.
Add the crate to your Cargo.toml
:
[dependencies]
itertools = "0.9.0"
Then use it in your file to sort and reverse the string.
use itertools::Itertools;
fn main() {
let wordy = "I am a hello world example";
let s = wordy.chars().sorted().rev().collect::<String>();
println!("{}", s);
}
Author by
user5335302
Updated on June 14, 2022Comments
-
user5335302 almost 2 years
I have the string "laxmi" and I need to sort it in descending alphabetical order, producing "xmlia". I have written this:
fn main() { let wordy: String = "I am a hello world example"; let chars: Vec<char> = wordy.chars().vector(); chars.sort_by(|a, b| b.cmp(a)); // let s: String = chars.into_iter().collect(); println!("test{:?}", chars); let s = String::from_iter(chars); println!("{}", s); }
This only works if
wordy
is a&str
, but I have aString
. How can I convert theString
to a vector ofchar
so that I can sort the string?