rust - 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
}
解决方案
所以这是张贴这种东西的错误地方,但如果任何其他锻炼学生通过谷歌搜索找到这个,我想指出 users.rustlang.org 上给出的好建议。
我发了一个类似的帖子,那里的人提出了一些非常好的建议。
推荐阅读
- javascript - 如何验证表单中的隐藏输入字段/更改验证行为?
- vue.js - 如果 Vue 中一个路径包含另一个路径,则导航栏一次选择两个抽屉
- git - 终端中提交的名称在github中不同
- node.js - 无法将 React-Bootstrap 与 Expo 一起使用(无法解析模块 react/jsx-runtime)
- java - Intellij 中的控制台日志格式已更改
- terraform - 尝试创建 azure 存储帐户并使用它来存储 terraform 状态文件
- python - 使用 statsmodels.tsa.seasonal.seasonal_decompose 分解营销效果
- python - 正则表达式:: 'pandas._libs.interval.Interval' 对象没有属性 'replace'
- docker - 使用 Docker 和 VSCode 设置 XDebug
- azure-eventgrid - Azure 事件网格 - 延迟执行