Trait join_string::Join
source · pub trait Join<I: Iterator> {
// Required method
fn iter(self) -> I;
// Provided methods
fn join<S>(self, sep: S) -> Joiner<I, S>
where Self: Sized,
S: Display,
I::Item: 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.
It is also implemented for a few common types that aren’t iterators, but
have an iter()
method. Among these types are arrays, slices, and Vec
s.
Required Methods§
Provided Methods§
sourcefn join<S>(self, sep: S) -> Joiner<I, S>where
Self: Sized,
S: Display,
I::Item: Display,
fn join<S>(self, sep: S) -> Joiner<I, S>where Self: Sized, S: Display, I::Item: Display,
Examples found in repository?
examples/reverse_words.rs (line 5)
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
pub fn reverse_words(s: impl AsRef<str>) -> String {
s.as_ref().split_whitespace()
.map(|s| s.chars().rev().join(""))
.join(" ")
.into_string()
}
fn main() {
println!("{}", reverse_words("foo bar baz"));
println!("{}",
"foo bar baz".split_whitespace()
.map(|s| s.chars().rev().join(""))
.join(" "));
println!("{}",
"foo bar baz".split_whitespace()
.map(|s| s.chars().rev().map(|c| char::from_u32(c as u32 + 1u32).unwrap_or('?')).join(""))
.join(" "));
// inefficient temporary strings
println!("{}",
"foo bar baz".split_whitespace()
.map(|s| s.chars().rev().map(|c| format!("<{c}>")).join(""))
.join(" "));
// inefficient temporary strings
println!("{}", std::env::args().map(|s| s.chars().rev().collect::<String>()).join(" ").into_string());
}
More examples
examples/file.rs (line 14)
6 7 8 9 10 11 12 13 14 15 16 17
fn main() -> std::io::Result<()> {
let mut args = std::env::args().skip(1);
let filename = args.next().expect(USAGE);
let sep = args.next().expect(USAGE);
let file = File::create(filename)?;
args.join(sep).write_io(file)?;
Ok(())
}
examples/simple.rs (line 4)
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
fn main() -> std::io::Result<()> {
println!("{}", ["foo", "bar", "baz"].iter().join(", "));
println!("{}", ['a', 'b', 'c'].iter().join(", "));
println!("{}", ["foo".to_owned(), "bar".to_owned(), "baz".to_owned()].iter().join(", "));
println!("{}", vec![1, 2, 3].iter().cycle().take(5).join(", "));
println!("{}", "äüö".chars().join(' '));
std::env::args().join(", ").write_io(std::io::stdout())?;
println!();
// inefficient temporary string
let str: String = std::env::args().join(", ").into();
println!("{}", str);
Ok(())
}