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

This tutorial demonstrates how to concatenate strings from a vector with a specified separator in Rust.

Rust Joining Strings in a Vector with a Separator

For example, suppose we have a list of strings stored in a vector object

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

We aim to iterate through the list of strings and concatenate them using a specified separator, such as a blank space or a hyphen.

Rust provides two methods for achieving this, introduced as of version 1.56.

  • join function

This function, introduced in version 1.3.0, takes a separator and returns the concatenated strings.

    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 (1.30), joins the strings of a vector and returns a single string.

Here’s 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 involves joining 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