program Rot13Demo;
{$mode objfpc}{$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).
*)
/// <summary>
/// Transforms a string using the ROT13 substitution cipher.
/// </summary>
/// <param name="AText">The input string (passed as const to prevent unnecessary copying)</param>
/// <returns>The transformed ROT13 string</returns>
function Rot13(const AText: string): string;
var
I: Integer;
C: Char;
begin
// Initialize the function's implicit 'Result' variable with the input string
Result := AText;
// Free Pascal strings are 1-indexed by default in ObjFPC mode
for I := 1 to Length(Result) do
begin
C := Result[I];
// Pascal's range matching in case statements makes handling ROT13 halves elegant
case C of
'a'..'m', 'A'..'M': Result[I] := Chr(Ord(C) + 13);
'n'..'z', 'N'..'Z': Result[I] := Chr(Ord(C) - 13);
end;
// Non-alphabetic characters (digits, punctuation, spaces) pass through unchanged
end;
end;
var
MessageText, Encrypted, Decrypted: string;
begin
MessageText := 'Hello, World! 123';
Writeln('Original: ', MessageText);
// Apply ROT13 encryption
Encrypted := Rot13(MessageText);
Writeln('ROT13: ', Encrypted);
// ROT13 is its own inverse; applying it again decrypts the text
Decrypted := Rot13(Encrypted);
Writeln('Decrypted: ', Decrypted);
end.
(*
run:
Original: Hello, World! 123
ROT13: Uryyb, Jbeyq! 123
Decrypted: Hello, World! 123
*)