How do I convert a Vector of bytes (u8) to a string
我试图在Rust中编写简单的TCP / IP客户端,我需要打印出从服务器获得的缓冲区。
如何将
要将字节片转换为字符串片(假设采用UTF-8编码):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | use std::str; // // pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> // // Assuming buf: &[u8] // fn main() { let buf = &[0x41u8, 0x41u8, 0x42u8]; let s = match str::from_utf8(buf) { Ok(v) => v, Err(e) => panic!("Invalid UTF-8 sequence: {}", e), }; println!("result: {}", s); } |
转换是就地的,不需要分配。 您可以根据需要通过在字符串切片上调用
转换功能的库参考:
-
std::str::from_utf8
我更喜欢
1 2 3 4 5 | fn main() { let buf = &[0x41u8, 0x41u8, 0x42u8]; let s = String::from_utf8_lossy(buf); println!("result: {}", s); } |
它将无效的UTF-8字节转换为? 因此不需要错误处理。 当您不需要它而我几乎不需要它时,它非常有用。 您实际上从中得到一个
有时您可能需要使用
如果您实际上有一个字节向量(
1 2 3 4 5 | fn main() { let bytes = vec![0x41, 0x42, 0x43]; let s = String::from_utf8(bytes).expect("Found invalid UTF-8"); println!("{}", s); } |