OneBite.Dev - Coding blog in a bite size

Split A String By A Delimiter In Rust

Code snippet for how to Split A String By A Delimiter In Rust with sample and detail explanation

In the world of programming, there are often tasks that require splitting a string based on a certain delimiter. This article seeks to guide you on how to accomplish this task using the Rust programming language.

Code snippet to Split a String by a Delimiter in Rust

Here’s a basic code snippet illustrating how a string can be split in Rust:

fn main(){
    let sample_string = "This,is,a,Sample,String";
    let split_string: Vec<&str> = sample_string.split(',').collect();
    println!("{:?}", split_string);
}

When you run the program, it will output: ["This", "is", "a", "Sample", "String"].

Code Explanation for Splitting a String by a Delimiter in Rust

In the Rust programming language, strings can be split using the split() function. This function is built-in and it breaks the string based on the specified delimiter then returns an iterator.

Firstly, we declare a string variable, sample_string, which we desire to split. The string is "This,is,a,Sample,String".

Secondly, we create a variable split_string that holds the result of the split operation. To perform the operation, we use sample_string.split(',') to split our string on each comma (,). However, this directly only creates an iterator.

To gather the results of the iterator into a format we can work with, we use the .collect() method to collect these results into a Vec<&str>.

Vec<&str> is a vector of string slices, each slice being a part of the original string cut at the delimiter.

Finally, we use the println!() macro to display our output. Here {:?} is used for formatting, it helps to print the structure as is. This will display an array of the string slices we collected.

Apply the methods as illustrated in the guide, and you should be able to split a string by a delimiter in Rust.

rust