Rust Program to Create random strings


Create random strings

Rust Programming Language


Create random strings


Problem


In Rust, we can generate random strings using the rand crate. Here's an example program that demonstrates how to create a random string of a given length.

Input


use rand::Rng;















 

fn main() {
    let length = 10;

    let mut rng = rand::thread_rng();

    let random_string: String = (0..length)
        .map(|_| rng.gen_range(b'a', b'z') as char)
        .collect();

    println!("{}", random_string);
}{codeBox}


Output


kfsqjwslct{codeBox}


Explanation


In this program, we first import the rand::Rng trait. We then set the length of the random string we want to generate to 10.

Next, we create a new rand::thread_rng() object, which is a thread-local random number generator. We then generate a random string of length 10 by using the map() method to generate a random character for each position in the string. We use the gen_range() method to generate a random integer in the range of b'a' to b'z' (inclusive), and then convert the integer to a character using the as char syntax. Finally, we collect the generated characters into a String using the collect() method.


Post a Comment