Convert A String To An Array In Rust
Code snippet for how to Convert A String To An Array In Rust with sample and detail explanation
Rust is a versatile programming language that presents multiple ways to manipulate data types according to your needs. This article will delve into one approach by demonstrating how to convert a string into an array in Rust.
Code snippet: Converting a String to an Array
The following code snippet shows how a String can be converted into an array in Rust.
let my_string = String::from("Hello, World!");
let my_array: Vec<&str> = my_string.split(' ').collect();
println!("{:?}", my_array);
When you execute the above code, the string “Hello, World!” is broken down into an array of words and the output will look like:
["Hello,", "World!"]
Code Explanation for Converting a String to an Array
The code snippet is simple and consists of three main steps to convert a String to an array.
-
let my_string = String::from("Hello, World!");
TheString::from
method is used to create a new string “Hello, World!” which we assign to themy_string
variable. -
let my_array: Vec<&str> = my_string.split(' ').collect();
Here, thesplit
method is called onmy_string
to split it into substrings whenever a whitespace character is encountered. Thesplit
method returns an iterator over the substrings. We then call thecollect
method, which transforms the iterator into a collection, in this case a vector of the substrings. This vector is stored in themy_array
variable. -
println!("{:?}", my_array);
Lastly, we print out the gathered vector (array), using the"{:?}"
formatting trait, which gives a debug representation of the value it is used with.
Essentially, the output is the result of splitting a string into words and collecting those words into a vector (which serves as an array). By the end, we obtain an array where each element is a word from the original string.
Keep in mind that this code snippet works well with strings that have space as a delimiter. If you want to split the string by another character, just replace the space inside the split()
method with the desired character.