如何将字符的迭代器转换为字符串? [英] How to convert iterator of chars to String?

查看:51
本文介绍了如何将字符的迭代器转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要类似 .collect() 的东西,但它会产生 String 而不是 char 的容器,即我需要一个相反的chars().我在文档中找不到任何合适的内容.我当然可以自己实现这样的功能,但我相信这个问题一定有标准的解决方案.

I need something like .collect() but which will produce String instead of container of chars, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆