Sort char in a String

Hi, I want to sort char in a String, e.g. input "acdbe", output "abcde". I changed &str to Vec<char>, sort it, then concat() it. But compiler said Output Type is not specified, how to solve it? Thanks!
BTW, is there any simpler approach?

fn main () {
    let s = "acdbe";
    let mut l:Vec<char> = s.chars().collect();
    l.sort_unstable();
    let j:String = l.concat();
    println!("{}",j);
}
error[E0599]: the method `concat` exists for struct `Vec<char>`, but its trait bounds were not satisfied
 --> src\main.rs:5:22
  |
5 |     let j:String = l.concat();
  |                      ^^^^^^ method cannot be called on `Vec<char>` due to unsatisfied trait bounds
  |
  = note: the following trait bounds were not satisfied:
          `<[char] as Concat<_>>::Output = _`

concat deals in strs, so you want collect again:

fn main() {
    let s = "acdbe";
    let mut l: Vec<char> = s.chars().collect();
    l.sort_unstable();
    let j: String = l.into_iter().collect();
    println!("{}", j);
}
1 Like

Thank you!

Note that Rust chars are Unicode scalar values, so you may get weird results when sorting them as you may break apart graphemes.

The unicode_segmentation crate can split on graphemes if that's better suited to your use case. (Although I'm sure this isn't proper Unicode collation either...)

4 Likes

Thank you!

For example, the sort may disperse the family.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.