加入& str的迭代器 [英] Join iterator of &str
问题描述
将 Iterator<& str>
转换为 String
并穿插一些常量字符串(例如"\ n"
)?
What is the canonical method to convert an Iterator<&str>
to a String
, interspersed with some constant string (e.g. "\n"
)?
例如,给定:
let xs = vec!["first", "second", "third"];
let it = xs.iter();
有一种方法可以通过收集一些 Iterable
和 join
生成结果来生成字符串 s
:
There is a way to produce a string s
by collecting into some Iterable
and join
ing the result:
let s = it
.map(|&x| x)
.collect::<Vec<&str>>()
.join("\n");
但是,这不必要地为 Vec& str>
分配了内存.有更直接的方法吗?
However, this unnecessarily allocates memory for a Vec<&str>
. Is there a more direct method?
推荐答案
您可以使用 itertools 板条箱.我使用 intersperse 在该示例中为a>助手,它几乎等同于迭代器的 join .
You could use the itertools crate for that. I use the intersperse helper in the example, it is pretty much the join equivalent for iterators.
cloned()
来将&& str
项转换为& str
项,它没有进行任何分配.当 rust@1.36
稳定发行时,最终可以将其替换为 copied()
.
cloned()
is needed to convert &&str
items to &str
items, it is not doing any allocations. It can be eventually replaced by copied()
when rust@1.36
gets a stable release.
use itertools::Itertools; // 0.8.0
fn main() {
let words = ["alpha", "beta", "gamma"];
let merged: String = words.iter().cloned().intersperse(", ").collect();
assert_eq!(merged, "alpha, beta, gamma");
}
这篇关于加入& str的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!