C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
String constructor: We pass our character array to the String constructor to convert it back into a String.
ArrayMain: Here we rotate a String, and then rotate the rotated string to see if it correctly round-trips (it does).
Java program that uses ROT13 cipher
public class Program {
public static String rot13(String value) {
char[] values = value.toCharArray();
for (int i = 0; i < values.length; i++) {
char letter = values[i];
if (letter >= 'a' && letter <= 'z') {
// Rotate lowercase letters.
if (letter > 'm') {
letter -= 13;
} else {
letter += 13;
}
} else if (letter >= 'A' && letter <= 'Z') {
// Rotate uppercase letters.
if (letter > 'M') {
letter -= 13;
} else {
letter += 13;
}
}
values[i] = letter;
}
// Convert array to a new String.
return new String(values);
}
public static void main(String[] args) {
// Rotate the input string.
// ... Then rotate the rotated string.
String input = "Do you have any cat pictures?";
String rot13 = rot13(input);
String roundTrip = rot13(rot13);
System.out.println(input);
System.out.println(rot13);
System.out.println(roundTrip);
}
}
Output
Do you have any cat pictures?
Qb lbh unir nal png cvpgherf?
Do you have any cat pictures?