Rust Program to Convert the Vec into a string and vice versa


Convert the Vec into a string and vice versa

Rust Programming Language


Convert the Vec into a string and vice versa


Problem


Program that demonstrates how to convert a Vec into a String and vice versa.

Input


fn main() {
    // Convert a Vec to a String
    let vec = vec!["foo", "bar", "baz"];
    let string = vec.join(",");
    println!("{}", string);

    // Convert a String to a Vec
    let string = String::from("foo,bar,baz");
    let vec: Vec<&str> = string.split(",").collect();
    println!("{:?}", vec);
}{codeBox}

Output


foo,bar,baz
["foo", "bar", "baz"]{codeBox}

Explanation


In this program, we first create a Vec of strings and then convert it into a comma-separated String using the join() method. We then print the resulting String to the console.

Next, we create a String containing comma-separated values and then convert it into a Vec of &str (string slices) using the split() method and collect() function. We then print the resulting Vec to the console.

The first line is the resulting String after converting the Vec to a String using the join() method.

The second line is the resulting Vec after converting the String to a Vec of &str using the split() method and collect() function.

Post a Comment