You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Unicode codepoint字符串转换为对应的Rust字符串

你可以直接借助Rust标准库的原生能力实现,不需要手动处理码点到UTF-8字节的转换逻辑,实现如下:

fn parse_unicode(input: &str) -> String {
    let codepoint = u32::from_str_radix(input, 16).expect("输入不是合法的十六进制字符串");
    char::from_u32(codepoint).expect("输入数值不是合法Unicode码点").to_string()
}

#[test]
fn test_parse_unicode() {
    let parsed_content = parse_unicode("1f44d");
    assert_eq!(parsed_content, String::from("\u{1f44d}"));
}

实现说明

  1. 调用u32::from_str_radix(input, 16)将输入的十六进制格式字符串解析为u32类型的码点数值,第二个参数16指定按十六进制规则解析
  2. 调用char::from_u32()将合法的码点值转换为Rust原生的char类型,Rust的char本身就是Unicode标量值,自动保证合法性
  3. 直接调用to_string()方法即可将char转换为UTF-8编码的String类型,全程不需要手动处理编码逻辑

如果你需要处理异常输入而不是直接panic,可以调整返回值为Result类型,示例如下:

#[derive(Debug, PartialEq)]
enum ParseUnicodeError {
    InvalidHex,
    InvalidCodepoint,
}

fn parse_unicode(input: &str) -> Result<String, ParseUnicodeError> {
    let codepoint = u32::from_str_radix(input, 16).map_err(|_| ParseUnicodeError::InvalidHex)?;
    let c = char::from_u32(codepoint).ok_or(ParseUnicodeError::InvalidCodepoint)?;
    Ok(c.to_string())
}

#[test]
fn test_parse_unicode() {
    let parsed_content = parse_unicode("1f44d").unwrap();
    assert_eq!(parsed_content, String::from("\u{1f44d}"));
}

内容的提问来源于stack exchange,提问作者Mindful

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:06:02