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

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>

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

/**
 * Encrypts/decrypts a null-terminated string in-place using the ROT13 cipher.
 *
 * @param str Pointer to the null-terminated string to transform.
 */
void rot13(char *str) {
    if (str == NULL) {
        return; // Guard against NULL pointer dereferences
    }

    for (int i = 0; str[i] != '\0'; i++) {
        char c = str[i];

        if (isupper(c)) {
            // Offset from 'A', shift by 13, wrap around with modulo 26
            str[i] = (c - 'A' + 13) % 26 + 'A';
        } else if (islower(c)) {
            // Offset from 'a', shift by 13, wrap around with modulo 26
            str[i] = (c - 'a' + 13) % 26 + 'a';
        }
        // Non-alphabetic characters (digits, punctuation, spaces) remain unchanged
    }
}

int main(void) {
    // Note: Must be a mutable character array, not a string literal (const char*)
    char message[] = "Hello, World! 123";

    printf("Original:  %s\n", message);

    // First pass: Encrypt
    rot13(message);
    printf("ROT13:     %s\n", message);

    // Second pass: Decrypt (ROT13 is self-inverse)
    rot13(message);
    printf("Decrypted: %s\n", message);

    return 0;
}


/*
run:

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

*/

 



answered Nov 4, 2016 by avibootz
edited 3 days ago by avibootz

Related questions

...