How to implement the ROT13 algorithm (replace a letter with the 13th letter after it) in Rust

1 Answer

0 votes
/*
ROT13 is a simple substitution cipher that replaces a letter with the 13th letter 
after it in the alphabet. Because the English alphabet has 26 letters (13 * 2), 
applying ROT13 twice restores the original text (it is its own inverse).
*/

/// Applies the ROT13 cipher to the input string.
///
/// ROT13 rotates each ASCII letter by 13 positions:
/// A ↔ N, B ↔ O, ..., M ↔ Z
/// a ↔ n, b ↔ o, ..., m ↔ z
///
/// Non-alphabetic characters are left unchanged.
///
/// Applying ROT13 twice returns the original text.
fn rot13(input: &str) -> String {
    input
        .chars()
        .map(|c| match c {
            // Rotate uppercase letters.
            'A'..='Z' => {
                let offset = c as u8 - b'A';
                (b'A' + (offset + 13) % 26) as char
            }

            // Rotate lowercase letters.
            'a'..='z' => {
                let offset = c as u8 - b'a';
                (b'a' + (offset + 13) % 26) as char
            }

            // Leave all other characters unchanged.
            _ => c,
        })
        .collect()
}

fn main() {
    let input = "Hello, World! 123";

    let encoded = rot13(input);
    let decoded = rot13(&encoded);

    println!("Input   : {}", input);
    println!("Encoded : {}", encoded);
    println!("Decoded : {}", decoded);
}


/*
run:

Input   : Hello, World! 123
Encoded : Uryyb, Jbeyq! 123
Decoded : Hello, World! 123

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...