{

How to join a Strings in a Vector into a String ain Rust example


This tutorials explains how to join a strings with separator from a Vector.

Rust Join strings in a Vector with separator

For example, We have a list of strings in a Vector object

    let numbers = vec!["One", "Two", "Three"];

You want to iterate the list of strings and join using separator. Separator can be blank space or hyphen.

Rust provides two methods as of version 1.56

  • join function

    This function addes since 1.3.0 version

    pub fn join<Separator>(&self, sep: Separator) -> <Self as Join<Separator>>::Output

These methods takes Separator and a string and return the join the strings

  • connect This function added in older version of 1.30, allows you to join the strings of a vector and return a string

Let’see an example of joing the strings with hypen(-)

fn main() {
    let numbers = vec!["One", "Two", "Three"];
    let result = numbers.join("-");
    let result1 = numbers.connect("-");

    println!("{}", result);
    println!("{}", result1);
}

Output:

One-Two-Three
One-Two-Three

Another example to join the strings using blank space

fn main() {
    let numbers = vec!["One", "Two", "Three"];
    let result = numbers.join(" ");
    let result1 = numbers.connect(" ");

    println!("{}", result);
    println!("{}", result1);
}

Output:

One Two Three
One Two Three
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.