OneBite.Dev - Coding blog in a bite size

Split A String In Rust

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

Rust is a powerful systems programming language that emphasizes concurrency, memory safety, and speed. In this article, we will delve into how to split a string in Rust, one of the many string manipulations you can perform with this language.

Code snippet for splitting a string

Here is an example of how to split a string in Rust:

fn main() {
    let s = "Hello, world!";
    let v: Vec<&str> = s.split(", ").collect();
    println!("{:?}", v);
}

Running this code will output:

["Hello", "world!"]

Code Explanation for splitting a string

In the example above, we used the split method followed by the collect method.

split is a method available to any instance of str in Rust. It takes as parameter a delimiter, that will be used to split the string. In our case, our delimiter is the comma and a space (”, ”). The split method returns an iterator over the substrings of the original string which are separated by the specified delimiter.

The collect method is used here to convert the iterator returned by split into a vector of strings (Vec<&str>). collect is a powerful method in Rust, which can transform an iterator into numerous different collections.

The println statement uses a {:?} debug string formatter to print each element of the vector v.

So, when you run the program, it splits the string “Hello, world!” into a vector of two strings “Hello” and “world!“.

This is just a simple demonstration of how you can split a string in Rust and collect it into a vector. Depending on your usage, you can choose various other methods in Rust for different types of string manipulation.

rust