pub trait Join<I: Iterator>: IntoIterator<IntoIter = I> {
// Provided methods
fn join<S>(self, sep: S) -> Joiner<I, S>
where Self: Sized,
S: Display { ... }
fn join_str<S>(self, sep: S) -> Joiner<DisplayIter<I>, DisplayWrapper<S>>
where Self: Sized,
S: AsRef<str>,
I::Item: AsRef<str> { ... }
}
Expand description
Trait that provides a method to join elements of an iterator, interspersing a separator between all elements.
This trait is implemented for anything that implements
std::iter::IntoIterator
, which is e.g. arrays, slices, Vec
, and more.
Provided Methods§
Sourcefn join<S>(self, sep: S) -> Joiner<I, S>
fn join<S>(self, sep: S) -> Joiner<I, S>
Join the elements of an iterator, interspersing a separator between all elements.
The elements and the separator need to implement std::fmt::Display
.
Examples found in repository?
examples/reverse_words.rs (line 6)
3pub fn reverse_words(s: impl AsRef<str>) -> String {
4 s.as_ref()
5 .split_whitespace()
6 .map(|s| s.chars().rev().join(""))
7 .join(" ")
8 .into_string()
9}
10
11fn main() {
12 println!("{}", reverse_words("foo bar baz"));
13
14 println!(
15 "{}",
16 "foo bar baz"
17 .split_whitespace()
18 .map(|s| s.chars().rev().join(""))
19 .join(" ")
20 );
21
22 println!(
23 "{}",
24 "foo bar baz"
25 .split_whitespace()
26 .map(|s| s
27 .chars()
28 .rev()
29 .map(|c| char::from_u32(c as u32 + 1).unwrap_or('?'))
30 .join(""))
31 .join(" ")
32 );
33
34 // inefficient temporary strings
35 println!(
36 "{}",
37 "foo bar baz"
38 .split_whitespace()
39 .map(|s| s.chars().rev().map(|c| format!("<{c}>")).join(""))
40 .join(" ")
41 );
42
43 // inefficient temporary strings
44 println!(
45 "{}",
46 std::env::args()
47 .map(|s| s.chars().rev().collect::<String>())
48 .join(" ")
49 .into_string()
50 );
51}
More examples
examples/file.rs (line 14)
6fn main() -> std::io::Result<()> {
7 let mut args = std::env::args().skip(1);
8
9 let filename = args.next().expect(USAGE);
10 let sep = args.next().expect(USAGE);
11
12 let file = File::create(filename)?;
13
14 args.join(sep).write_io(file)?;
15
16 Ok(())
17}
examples/simple.rs (line 4)
3fn main() -> std::io::Result<()> {
4 println!("{}", ["foo", "bar", "baz"].join(", "));
5 println!("{}", ['a', 'b', 'c'].join(", "));
6 println!(
7 "{}",
8 ["foo".to_owned(), "bar".to_owned(), "baz".to_owned()].join(", ")
9 );
10 println!("{}", vec![1, 2, 3].iter().cycle().take(5).join(", "));
11 println!("{}", "äüö".chars().join(' '));
12 std::env::args().join(", ").write_io(std::io::stdout())?;
13 println!();
14
15 // inefficient temporary string
16 let str: String = std::env::args().join(", ").into();
17 println!("{}", str);
18
19 Ok(())
20}
Sourcefn join_str<S>(self, sep: S) -> Joiner<DisplayIter<I>, DisplayWrapper<S>>
fn join_str<S>(self, sep: S) -> Joiner<DisplayIter<I>, DisplayWrapper<S>>
Join the elements of an iterator, interspersing a separator between all elements.
The elements and the separator need to implement AsRef<str>
.