如何将字符的迭代器转换为字符串? [英] How to convert iterator of chars to String?
问题描述
我需要类似 .collect()
的东西,但它会产生 String
而不是 char
的容器,即我需要一个相反的chars().我在文档中找不到任何合适的内容.我当然可以自己实现这样的功能,但我相信这个问题一定有标准的解决方案.
I need something like .collect()
but which will produce String
instead of container of char
s, i.e. I need an inverse of chars(). I cannot find anything suitable in the documentation. Of course I can implement such a function myself but I'm sure there must be standard solution to this problem.
我使用的是稳定版 Rust.
I'm using stable Rust.
推荐答案
.collect()
在它生成的集合中是通用的,它可以生成 String
用于你!
.collect()
is generic in what collection it produces, and it can produce the String
for you!
let s = "abc".chars().collect::<String>();
特征 FromIterator
决定了你可以使用哪些元素收集到哪种集合中,在实现者中可以找到两次String
:
impl FromIterator<char> for String
impl<'a> FromIterator<&'a str> for String
char
和 &str
的迭代器都可以收集到 String
中.
Both iterators of char
and of &str
can be collected to String
.
这篇关于如何将字符的迭代器转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!