Shift Text With A Caesar Cipher
Rotate lowercase letters through the 26-letter ring with rem_euclid so negative shifts decode correctly and non-letters pass through.
Code
// Caesar cipher 只旋转小写字母,其余字符原样保留
fn shift(text: &str, k: i8) -> String {
text.chars()
.map(|c| match c {
'a'..='z' => {
let pos = (c as u8 - b'a') as i32;
// rem_euclid 把位移折进 0..26 的环:负位移也能正确回读
let ring = (pos + k as i32).rem_euclid(26);
(b'a' + ring as u8) as char
}
_ => c,
})
.collect()
}
fn main() {
let plain = "attack at dawn";
let cipher = shift(plain, 3);
println!("cipher: {cipher}");
let decoded = shift(&cipher, -3);
println!("decoded: {decoded}");
println!("roundtrip ok: {}", decoded == plain);
}How the snippet works
The working surface is the functions shift and main — everything else is wiring.
Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Applying it
The entry-point signature is fn shift(text: &str, k: i8) -> String
The demo output is labeled (cipher:, decoded:, roundtrip ok:); each label names the call that printed it.
There are 1 call inside main — shift — executed top to bottom.
Statements that matter
.map(|c| match c {
'a'..='z' => {
let pos = (c as u8 - b'a') as i32;
// rem_euclid 把位移折进 0..26 的环:负位移也能正确回读
let ring = (pos + k as i32).rem_euclid(26);
(b'a' + ring as u8) as char
}
_ => c,
})
Interactive Tools for This Topic
Caesar CipherShift letters by any integer amount to encode or decode Caesar ciphers, with case preservation and automatic round-trip verification.ROT13 EncoderApply the ROT13 letter rotation to any text: letters shift thirteen places, non-letters pass through, and the transform is self-inverse.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vigenere CipherEncode and decode Vigenere ciphers with alphabetic keys, preserving case and passing non-letters through unshifted.
FAQ
- What does Shift Text With A Caesar Cipher print when run?
- The script runs standalone; its 3 labeled outputs include `cipher:`, `decoded:`, `roundtrip ok:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.