string 如何将 Vec<char> 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23430735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Vec<char> to a string
提问by user3596561
How to convert Vec<char>
to string form so that I can print it?
如何转换Vec<char>
为字符串形式以便我可以打印它?
回答by Vladimir Matveev
Use collect()
on an iterator:
使用collect()
上的迭代器:
let v = vec!['a', 'b', 'c', 'd'];
let s: String = v.into_iter().collect();
println!("{}", s);
The original vector will be consumed. If you need to keep it, use v.iter()
:
原始向量将被消耗。如果您需要保留它,请使用v.iter()
:
let s: String = v.iter().collect();
There is no more direct way because char
is a 32-bit Unicode scalar value, and strings in Rust are sequences of bytes (u8
) representing text in UTF-8 encoding. They do not map directly to sequences of char
s.
没有更直接的方法,因为char
是 32 位 Unicode 标量值,而 Rust 中的字符串是u8
表示 UTF-8 编码文本的字节序列 ( )。它们不直接映射到char
s 的序列。
回答by malbarbo
Here is a more readable version that consumes the vector:
这是一个更易读的使用向量的版本:
use std::iter::FromIterator;
fn main() {
let v = vec!['a', 'b', 'c', 'd'];
let s = String::from_iter(v);
// vs
let s: String = v.into_iter().collect();
}
Note that collect
is implemented with a call to FromIterator::from_iter
:
请注意,这collect
是通过调用实现的FromIterator::from_iter
:
fn collect<B: FromIterator<Self::Item>>(self) -> B
where
Self: Sized,
{
FromIterator::from_iter(self)
}