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

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

public class Rot13Demo {

    /**
     * Transforms a string using the ROT13 substitution cipher.
     * 
     * @param text The input string to transform.
     * @return A new string with the ROT13 cipher applied, or null if input is null.
     */
    public static String rot13(String text) {
        if (text == null) {
            return null; // Guard against null pointer exceptions
        }

        // Use StringBuilder with pre-allocated capacity for optimal performance
        StringBuilder result = new StringBuilder(text.length());

        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);

            if (c >= 'a' && c <= 'z') {
                // Shift lowercase letters by 13, wrapping around with modulo 26
                result.append((char) ((c - 'a' + 13) % 26 + 'a'));
            } else if (c >= 'A' && c <= 'Z') {
                // Shift uppercase letters by 13, wrapping around with modulo 26
                result.append((char) ((c - 'A' + 13) % 26 + 'A'));
            } else {
                // Non-alphabetic characters (digits, spaces, punctuation) pass through untouched
                result.append(c);
            }
        }

        return result.toString();
    }

    public static void main(String[] args) {
        String message = "Hello, World! 123";

        System.out.println("Original:  " + message);

        // Apply ROT13 encryption
        String encrypted = rot13(message);
        System.out.println("ROT13:     " + encrypted);

        // ROT13 is its own inverse; applying it again decrypts the message
        String decrypted = rot13(encrypted);
        System.out.println("Decrypted: " + decrypted);
    }
}


/*
run:

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

*/

 



answered 3 days ago by avibootz

Related questions

...