How to shuffle a string in Rust

1 Answer

0 votes
use rand::seq::SliceRandom; // shuffle

fn shuffle_string(s: &str) -> String {
    let mut chars: Vec<char> = s.chars().collect(); // convert string to vector
    let mut rng = rand::thread_rng();
    
    chars.shuffle(&mut rng); // shuffle the vector
    
    chars.into_iter().collect() // convert the shuffled vector back into a string
}

fn main() {
    let s = "Rust Programming";
    
    let shuffled = shuffle_string(s);
    
    println!("{}", shuffled);
}



/*
run:
  
rgom mairugRsPnt
  
*/

 



answered Nov 4, 2024 by avibootz
...