如何转换 Vec<char>到一个字符串 [英] How to convert Vec&lt;char&gt; to a string

查看:40
本文介绍了如何转换 Vec<char>到一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Vec 转换为字符串形式以便打印?

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

推荐答案

在迭代器上使用 collect():

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

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

The original vector will be consumed. If you need to keep it, use v.iter():

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

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

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.

这篇关于如何转换 Vec<char>到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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