The Join() method in C# is used to concatenate all the elements of a string array, using the specified separator between each element.
The join() string method returns a string by joining all the elements of an iterable (list, string, tuple), separated by a string separator.
Rust provides multiple ways to concatenate or join Strings, but the easiest of them is by using += operator.
join() There is another, more powerful, way to join strings together. You can go from a list to a string in Python with the join() method. The common use case here is when you have an iterable—like a list—made up of strings, and you want to combine those strings into a single string.
In Rust 1.3.0 and later, join
is available:
fn main() {
let string_list = vec!["Foo".to_string(),"Bar".to_string()];
let joined = string_list.join("-");
assert_eq!("Foo-Bar", joined);
}
Before 1.3.0 this method was called connect
:
let joined = string_list.connect("-");
Note that you do not need to import anything since the methods are automatically imported by the standard library prelude.
As mentioned by Wilfred, SliceConcatExt::connect
has been deprecated since version 1.3.0 in favour of SliceConcatExt::join
:
let joined = string_list.join("-");
There is a function from the itertools
crate also called join
which joins an iterator:
extern crate itertools; // 0.7.8
use itertools::free::join;
use std::fmt;
pub struct MyScores {
scores: Vec<i16>,
}
impl fmt::Display for MyScores {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("MyScores(")?;
fmt.write_str(&join(&self.scores[..], &","))?;
fmt.write_str(")")?;
Ok(())
}
}
fn main() {
let my_scores = MyScores {
scores: vec![12, 23, 34, 45],
};
println!("{}", my_scores); // outputs MyScores(12,23,34,45)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With