首页 > 解决方案 > 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}"));
}

我看到有一个从字节数组到字符串的函数,所以如果我自己编写代码来将这些代码点解析为字节数组,我可以将它们转换为字符串,但我希望有一个更惯用的(或至少更容易) 方法。

标签: rustunicodeutf-8

解决方案


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(''));
}

推荐阅读