-4

I would like to create a sorted word from a String

Here is what I have so far.

fn sort_word(word: &str) -> String {
    word.chars()
        .collect::<Vec<char>>()
        .sort_unstable()
        .iter()
        .collect()
}

I do not understand the compiler message :

error[E0599]: no method named `iter` found for unit type `()` in the current scope
 --> src/lib.rs:5:10
  |
5 |         .iter()
  |          ^^^^ method not found in `()`

What am I doing wrong here?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Chapo
  • 2,563
  • 3
  • 30
  • 60
  • 1
    `sort_unstable` doesn't return a value (which is the same as returning `()`). It just sorts the given slice. – interjay Jul 21 '21 at 08:11
  • [That sorting method](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.sort_unstable) does not return the sorted slice. Prefer doing what's advised here: https://stackoverflow.com/q/54701548 – E_net4 Jul 21 '21 at 08:13
  • ah that's it ok ! Thanks for pointing the obvious. Yes I used sorted intially but wanted to give it a crack with only `std` – Chapo Jul 21 '21 at 08:14

2 Answers2

1

In case it helps anyone

fn sort_word(word: &str) -> String {
    let mut cvec = word.chars().collect::<Vec<_>>();
    cvec.sort_unstable();
    cvec.iter().collect()
}
eggyal
  • 122,705
  • 18
  • 212
  • 237
Chapo
  • 2,563
  • 3
  • 30
  • 60
0

Just for fun and to have another option, you could use a HashMap to count the items and then reconstruct the whole string.

Here is an example for ASCII characters:

use std::collections::HashMap;
use std::iter;

fn sort_string(s: &str) -> String {
    let mut counter = HashMap::new();
    for c in s.chars() {
        *counter.entry(c).or_insert(0usize) += 1;
    }
    (0..=255)
        .map(char::from)
        .filter_map(|c| counter.get(&c).map(|n| iter::repeat(c).take(*n)))
        .flatten()
        .collect()
}

Playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • Thanks for taking the time to answer. Could you please explain why your solution is better than the first one posted ? How does one run timing comparisons in Rust ? – Chapo Jul 22 '21 at 05:28
  • @Chapo, I'm not sure about running time. But It is constant time up to 255 in intermediate allocation since you do not need to build the intermediate vec. For running time we would have to run some benchmarks. Ill bench them later and update when I have time for it :) – Netwave Jul 22 '21 at 07:45