Implementing ROT13 in Different Languages
See ROT13 implementations in JavaScript, Python, Bash, C, Go, and Rust. Compare approaches using string manipulation, character arithmetic, and standard library functions.
Detailed Explanation
ROT13 Implementations Across Languages
ROT13 is a classic programming exercise that reveals interesting differences between languages. Here are idiomatic implementations in several popular languages.
JavaScript
const rot13 = str => str.replace(/[a-zA-Z]/g, c =>
String.fromCharCode(c.charCodeAt(0) + (c.toLowerCase() < 'n' ? 13 : -13))
);
This one-liner uses a regex to find letters and shifts them, choosing +13 or -13 based on whether the character is in the first or second half of the alphabet.
Python
import codecs
decoded = codecs.decode("Uryyb, Jbeyq!", "rot_13")
# "Hello, World!"
Python includes ROT13 as a built-in codec. For a manual implementation:
def rot13(text):
return text.translate(str.maketrans(
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
))
Bash
echo "Hello, World!" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
# Uryyb, Jbeyq!
The classic Unix approach using the tr (translate) command.
C
void rot13(char *str) {
for (; *str; str++) {
if ((*str >= 'A' && *str <= 'Z') || (*str >= 'a' && *str <= 'z')) {
char base = (*str >= 'a') ? 'a' : 'A';
*str = base + (*str - base + 13) % 26;
}
}
}
Go
func rot13(s string) string {
return strings.Map(func(r rune) rune {
switch {
case r >= 'A' && r <= 'Z':
return 'A' + (r-'A'+13)%26
case r >= 'a' && r <= 'z':
return 'a' + (r-'a'+13)%26
default:
return r
}
}, s)
}
Rust
fn rot13(input: &str) -> String {
input.chars().map(|c| match c {
'A'..='Z' => (b'A' + (c as u8 - b'A' + 13) % 26) as char,
'a'..='z' => (b'a' + (c as u8 - b'a' + 13) % 26) as char,
_ => c,
}).collect()
}
Key Differences
- Python has ROT13 built into the standard library
- Bash achieves it with a single
trcommand - JavaScript uses regex replace with a callback
- C/Go/Rust use explicit character arithmetic with modulo
Use Case
ROT13 implementations are commonly used in programming tutorials, coding interviews, and as a warm-up exercise in competitive programming. Comparing implementations across languages helps developers understand string handling, character encoding, and idiomatic patterns.