How to convert Vec to a string

2019-01-18 17:37发布

How to convert Vec<char> to string form so that I can print it?

标签: string rust
3条回答
神经病院院长
2楼-- · 2019-01-18 18:00

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:

fn collect<B: FromIterator<Self::Item>>(self) -> B
where
    Self: Sized,
{
    FromIterator::from_iter(self)
}
查看更多
冷血范
3楼-- · 2019-01-18 18:08

Use collect() on an iterator:

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():

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 chars.

查看更多
成全新的幸福
4楼-- · 2019-01-18 18:22

Editor's note: This answer was correct for versions of Rust before 1.0 but is now out-of-date (from_chars doesn't exist, and std::strbuf::StrBuf is now just String). Other answers have been updated to address Rust 1.0.

std::str::from_chars(char_vector.as_slice()); // creates a ~str

char_vector.iter().map(|c| *c).collect::<std::strbuf::StrBuf>();

Docs: std::str::from_chars

(The latter can be used to collect to a ~str too, just by changing the StrBuf type hint.)

查看更多
登录 后发表回答