首页 > 解决方案 > Rust 中的 Atbash 密码

问题描述

所以我正在为 Rust 实现 Atbash Cipher - 这是 exercism.io 上的一个练习。我有一点 C 经验,发现我的代码相当圆润,有点受折磨。在 Rust 中进行 str 和 String 操作是我还没有真正理解的事情。看起来这将占用更少的 C 代码行。

下面是我的代码 - 我是否以正确的方式处理 Rust,或者我是否遗漏了一些重要的概念或数据分解方式?这是应该的那么简单吗?

该练习涉及获取输入&str和输出 a String,每个字符根据 atbash 密码进行更改,每 5 个字符添加一个空格。包括也是一个decode功能。这一切都在一个lib.rs.

// "Encipher" with the Atbash cipher.
pub fn encode(plain: &str) -> String {
    let mut coded: String = plain.to_string();

    coded.retain(|c| c.is_ascii_alphanumeric());
    coded.make_ascii_lowercase();

    let coded_no_spacing = String::from_utf8(
        coded
            .bytes()
            .map(|c| {
                if c.is_ascii_alphabetic() {
                    122 - c + 97
                } else {
                    c
                }
            })
            .collect(),
    )
    .unwrap();

    spacer(coded_no_spacing)
}

/// "Decipher" with the Atbash cipher.
pub fn decode(cipher: &str) -> String {
    let mut out = encode(cipher);
    out.retain(|c| c.is_ascii_alphanumeric());
    out
}

fn spacer(coded_no_spacing: String) -> String {
    let mut coded_no_spacing = coded_no_spacing.chars();

    let mut temp_char = coded_no_spacing.next();
    let mut counter = 0;
    let mut coded_with_spaces = "".to_string();
    while temp_char.is_some() {
        if counter % 5 == 0 && counter != 0 {
            coded_with_spaces.push(' ');
        }
        coded_with_spaces.push(temp_char.unwrap());
        temp_char = coded_no_spacing.next();
        counter += 1;
    }
    coded_with_spaces
}

标签: rust

解决方案


所以这是张贴这种东西的错误地方,但如果任何其他锻炼学生通过谷歌搜索找到这个,我想指出 users.rustlang.org 上给出的好建议。

我发了一个类似的帖子,那里的人提出了一些非常好的建议


推荐阅读