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

1 Answer

0 votes
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

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

/**
 * @brief Transforms a string using the ROT13 substitution cipher.
 * 
 * @param text The input string (passed by value to support both lvalues and rvalues efficiently).
 * @return std::string The processed ROT13 string.
 */
std::string rot13(std::string text) {
    // std::transform applies a unary operation across the range [begin, end)
    std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) {
        if (std::isupper(c)) {
            // Shift uppercase letters by 13, wrapping around with modulo 26
            return static_cast<char>((c - 'A' + 13) % 26 + 'A');
        } 
        if (std::islower(c)) {
            // Shift lowercase letters by 13, wrapping around with modulo 26
            return static_cast<char>((c - 'a' + 13) % 26 + 'a');
        }
        // Non-alphabetic characters (spaces, punctuation, digits) remain untouched
        return static_cast<char>(c);
    });
    
    return text;
}

int main() {
    // Modern C++ string management (safe, dynamic size, no manual buffer sizing)
    std::string message = "Hello, World! 123";

    std::cout << "Original:  " << message << '\n';

    // Apply ROT13 encryption
    std::string encrypted = rot13(message);
    std::cout << "ROT13:     " << encrypted << '\n';

    // ROT13 is its own inverse; applying it again decrypts the message
    std::string decrypted = rot13(encrypted);
    std::cout << "Decrypted: " << decrypted << '\n';
}


/*
run:

Original:  Hello, World! 123
ROT13:     Uryyb, Jbeyq! 123
Decrypted: Hello, World! 123

*/

 



answered 3 days ago by avibootz

Related questions

...