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

This tutorial explains how to join a string with separator from a Vector.

Rust Join strings in a Vector with a 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 a separator. The separator can be a blank space or a hyphen.

Rust provides two methods as of version 1.56

  • join function

    This function was added in the 1.3.0 version

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

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

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

Lets an example of joining the strings with a hyphen(-)

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 is to join the strings using a 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