有没有一种方法可以在Rust中为字符添加偏移量?

时间:2019-09-11 16:59:42

标签: string rust character ascii

我来自C / C ++背景,其中ASCII字节很容易偏移:

char my_new_char = 'a' + some_offset;

据我了解,Rust在其char / &str / String中使用UTF-8,因此偏移量并非在所有范围内都可用。但是,以这种方式进行偏移对于ASCII范围内的字符仍然应该可行,对吗? UTF-8将ASCII镜像为重叠范围。

我正在查看文档/搜索,但是找不到抵消的方法。在Rust中有可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

fn f(c: char, n: i8) -> char {
    debug_assert!(c.is_ascii_alphanumeric());
    let ret = ((c as i8) + n) as u8 as char;
    debug_assert!(ret.is_ascii_alphanumeric());
    ret
}

这允许正向和负向偏移,并确保输入和输出都在[a-zA-Z0-9]范围内(这通常是您在此情况下想要的)。

相关问题