rust - Unicode 代码点到 Rust 字符串
问题描述
我只是在学习 Rust,所以如果有一种我错过的简单方法可以做到这一点,我深表歉意。我有一个程序在运行时将 unicode 代码点作为字符串获取,我想将这些代码点转换为包含它们所代表的字符的 Rust 字符串。基本上,我试图弄清楚如何parse_unicode
为下面的代码定义。
fn parse_unicode(input: &str) -> String {
input.to_string() // not working implementation
}
#[test]
fn test_parse_unicode() {
let parsed_content = parse_unicode("1f44d");
assert_eq!(parsed_content, String::from("\u{1f44d}"));
}
我看到有一个从字节数组到字符串的函数,所以如果我自己编写代码来将这些代码点解析为字节数组,我可以将它们转换为字符串,但我希望有一个更惯用的(或至少更容易) 方法。
解决方案
Stargateur 基本上解决了我在评论中链接代码的问题,如下所示:
use std::num::ParseIntError;
#[derive(Debug, PartialEq)]
enum Error {
Int(ParseIntError),
Unicode(u32),
}
fn parse_unicode(input: &str) -> Result<char, Error> {
let unicode = u32::from_str_radix(input, 16).map_err(Error::Int)?;
char::from_u32(unicode).ok_or_else(|| Error::Unicode(unicode))
}
#[test]
fn test_parse_unicode() {
assert_eq!(parse_unicode("1f44d"), Ok(''));
}
推荐阅读
- google-cloud-platform - 无法在 GCP 平台上安装 Openshift
- sparql - SPARQL 和链接数据:获取外部属性的属性
- javascript - 如何在 React 的另一个类上调用 const?
- exception - System.Runtime.InteropServices.COMException:错误?
- javascript - Vuetify/Javascript 为什么我得到一个 ReferenceError: variable is not defined
- javascript - 如何使用 Express/Pug 动态呈现异步函数输出?
- python - IronPython.Runtime.UnboundNameException:'名称'true'未定义'
- sql - 根据行值和上一行值重置 ROW_NUMBER?
- c# - 启动进程 WMI 在另一台计算机上最大化
- oracle - Oracle Apex 交互式报表标题过滤器大小