如何将Vec <char>转换为字符串


79

如何转换Vec<char>为字符串形式以便可以打印?

Answers:


123

使用collect()上的迭代器:

let v = vec!['a', 'b', 'c', 'd'];
let s: String = v.into_iter().collect();
println!("{}", s);

原始向量将被消耗。如果需要保留它,请使用v.iter()

let s: String = v.iter().collect();

没有更直接的方法,因为char它是32位Unicode标量值,Rust中的字符串是字节序列(u8),表示UTF-8编码的文本。它们不直接映射到chars的序列。


27

这是使用向量的更具可读性的版本:

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();
}

请注意,这collect是通过调用来实现的FromIterator::from_iter

fn collect<B: FromIterator<Self::Item>>(self) -> B
where
    Self: Sized,
{
    FromIterator::from_iter(self)
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.