如果我不在乎特定的编码,如何将u8切片作为文本打印? [英] How to print a u8 slice as text if I don't care about the particular encoding?

查看:80
本文介绍了如果我不在乎特定的编码,如何将u8切片作为文本打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 println!( {:?},some_u8_slice)在Rust中打印 u8 数组时;

When printing a u8 array in Rust using println!("{:?}", some_u8_slice); this prints the numeric values (as it should).

将字符原样格式化为字符串
的最直接方法是什么,而无需假设任何特殊的方法是什么?

What is the most direct way to format the characters as-is into the string without assuming any particular encoding.

类似的操作,遍历字节字符串并将每个字符写入 stdout

Something like iterating over the byte string and writing each character to the stdout (without so much hassle).

可以使用Rusts 格式完成此操作!吗?

Can this be done using Rusts format!?

否则,打印u8切片最方便的方法是什么?

Otherwise whats the most convenient way to print a u8 slice?

推荐答案

最简单的方法是 stdout()。write_all(some_u8_slice)。这将只输出字节,而不考虑其编码。这对于二进制数据或要保留原始编码的未知编码文本很有用。

The simplest way is stdout().write_all(some_u8_slice). This will simply output the bytes, with no regard for their encoding. This is useful for binary data, or text in some unknown encoding where you want to preserve the original encoding.

如果要将数据视为字符串,并且知道如果编码为UTF-8(或类似ASCII的UTF-8子集),则可以执行以下操作:

If you want to treat the data as a string and you know that the encoding is UTF-8 (or a UTF-8 subset like ASCII) then you can do this:

use std::str;

fn main() {
    let some_utf8_slice = &[104, 101, 0xFF, 108, 111];
    if let Ok(s) = str::from_utf8(some_utf8_slice) {
        println!("{}", s);
    }
}

这将检查数据是否有效UTF-8在打印之前。

This will check that the data is valid UTF-8 before printing it.

这篇关于如果我不在乎特定的编码,如何将u8切片作为文本打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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