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

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).
*/

import Foundation

/// Applies the ROT13 cipher to the given string.
///
/// ROT13 rotates each letter by 13 positions in the alphabet:
/// 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.
///
/// - Parameter input: The text to encode or decode.
/// - Returns: The ROT13-transformed string.
func rot13(_ input: String) -> String {
    String(input.map { character in
        guard let ascii = character.asciiValue else {
            return character
        }

        switch ascii {
        case UInt8(ascii: "A")...UInt8(ascii: "Z"):
            // Rotate uppercase letters.
            let offset = ascii - Character("A").asciiValue!
            return Character(UnicodeScalar(
                Character("A").asciiValue! + (offset + 13) % 26
            ))

        case UInt8(ascii: "a")...UInt8(ascii: "z"):
            // Rotate lowercase letters.
            let offset = ascii - Character("a").asciiValue!
            return Character(UnicodeScalar(
                Character("a").asciiValue! + (offset + 13) % 26
            ))

        default:
            // Leave digits, spaces, punctuation, etc. unchanged.
            return character
        }
    })
}

let input = "Hello, World! 123"

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

print("Input   : \(input)")
print("Encoded : \(encoded)")
print("Decoded : \(decoded)")


/*
run:

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

*/

 



answered 2 days ago by avibootz

Related questions

...