OneBite.Dev - Coding blog in a bite size

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.

  1. let my_string = String::from("Hello, World!"); The String::from method is used to create a new string “Hello, World!” which we assign to the my_string variable.

  2. let my_array: Vec<&str> = my_string.split(' ').collect(); Here, the split method is called on my_string to split it into substrings whenever a whitespace character is encountered. The split method returns an iterator over the substrings. We then call the collect method, which transforms the iterator into a collection, in this case a vector of the substrings. This vector is stored in the my_array variable.

  3. 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.

rust