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

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

package main

import (
	"fmt"
	"strings"
)

// rot13Rune applies the ROT13 transformation logic to an individual rune.
func rot13Rune(r rune) rune {
	switch {
	case r >= 'a' && r <= 'z':
		// Shift lowercase letters by 13, wrapping around with modulo 26
		return 'a' + (r-'a'+13)%26
	case r >= 'A' && r <= 'Z':
		// Shift uppercase letters by 13, wrapping around with modulo 26
		return 'A' + (r-'A'+13)%26
	default:
		// Non-alphabetic characters (digits, spaces, punctuation) pass through untouched
		return r
	}
}

// rot13 transforms an input string using the ROT13 substitution cipher.
func rot13(text string) string {
	// strings.Map efficiently applies a mapping function to all characters (runes) in the string
	return strings.Map(rot13Rune, text)
}

func main() {
	// Input string specified
	message := "Hello, World! 123"

	fmt.Printf("Original:  %s\n", message)

	// Apply ROT13 encryption
	encrypted := rot13(message)
	fmt.Printf("ROT13:     %s\n", encrypted)

	// ROT13 is its own inverse; applying it again decrypts the message
	decrypted := rot13(encrypted)
	fmt.Printf("Decrypted: %s\n", decrypted)
}


/*
run:

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

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...