gpt4 book ai didi

rust - 在Rust中将文本数字解析为UTF-8字符?

转载 作者:行者123 更新时间:2023-12-03 11:41:55 25 4
gpt4 key购买 nike

我有一个字节数组,其中的UTF8字节为str。
我想将此数组转换为UTF8字符。

像这样

["21", "22", "23", "24"]: [&str]


!"#$

最佳答案

use std::convert::TryFrom;

fn main() {
let input = ["21", "22", "23", "24"];

let result: String = input
.iter()
.map(|s| u32::from_str_radix(s, 16).unwrap()) // HEX string to unsigned int
.map(|u| char::try_from(u).unwrap()) // unsigned int to char (unicode verification)
.collect();

assert_eq!(result, "!\"#$");
}

然后,如果需要,可以添加错误验证,而不是 unwrap。我会用一个迭代器来做到这一点:
use std::convert::TryFrom;
use std::error::Error;

struct HexSliceToChars<'a> {
slice: &'a [&'a str],
index: usize,
}

impl<'a> HexSliceToChars<'a> {
fn new(slice: &'a [&'a str]) -> Self {
HexSliceToChars {slice, index: 0 }
}
}

impl<'a> Iterator for HexSliceToChars<'a> {
type Item = Result<char, Box<dyn Error>>;

fn next(&mut self) -> Option<Self::Item> {
self.slice.get(self.index).map(|s| {
let u = u32::from_str_radix(s, 16)?;
let c = char::try_from(u)?;

self.index += 1;

Ok(c)
})
}
}

fn main() {
let input = ["21", "22", "23", "24"];
let result: Result<String, _> = HexSliceToChars::new(&input).collect();
// Error handling
let result = result.unwrap();

assert_eq!(result, "!\"#$");
}

关于rust - 在Rust中将文本数字解析为UTF-8字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62211166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com