Is there already a rot13()
and unrot13()
implementation as part of one of the standard Java libraries? Or do I have to write it myself and "reinvent the wheel"?
It might look something like this:
int rot13 ( int c ) {
if ( (c >= 'A') && (c <= 'Z') )
c=(((c-'A')+13)%26)+'A';
if ( (c >= 'a') && (c <= 'z') )
c=(((c-'a')+13)%26)+'a';
return c;
}
Explanation of ROT13 AlgorithmROT13 cipher refers to the abbreviated form Rotate by 13 places. It is a special case of Caesar Cipher in which shift is always 13. Every letter is shifted by 13 places to encrypt or decrypt the message.
Introduction. The ROT13 cipher is a substitution cipher with a specific key where the letters of the alphabet are offset 13 places. I.e. all 'A's are replaced with 'N's, all 'B's are replaced with 'O's, and so on. It can also be thought of as a Caesar cipher with a shift of 13.
ROT13 ("rotate by 13 places", usually hyphenated ROT-13) is a simple Caesar cipher used for obscuring text by replacing each letter with the letter thirteen places down the alphabet.
ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. ROT13 is a special case of the Caesar cipher which was developed in ancient Rome.
Might as well contribute my function to save other developers the valuable seconds
public static String rot13(String input) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 'a' && c <= 'm') c += 13;
else if (c >= 'A' && c <= 'M') c += 13;
else if (c >= 'n' && c <= 'z') c -= 13;
else if (c >= 'N' && c <= 'Z') c -= 13;
sb.append(c);
}
return sb.toString();
}
I don't think it's part of Java by default, but here's an example of how you can implement it;
public class Rot13 {
public static void main(String[] args) {
String s = args[0];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'm') c += 13;
else if (c >= 'A' && c <= 'M') c += 13;
else if (c >= 'n' && c <= 'z') c -= 13;
else if (c >= 'N' && c <= 'Z') c -= 13;
System.out.print(c);
}
System.out.println();
}
}
Source: http://introcs.cs.princeton.edu/java/31datatype/Rot13.java.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With