Convert the Vec into a string and vice versa
Rust Programming Language
Problem
Program that demonstrates how to convert a Vec into a String and vice versa.
Input
fn main() {// Convert a Vec to a Stringlet vec = vec!["foo", "bar", "baz"];let string = vec.join(",");println!("{}", string);// Convert a String to a Veclet 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.