Java, How to implement a Shift Cipher (Caesar Cipher)
Java Shift Caesar Cipher by shift
spaces.
Restrictions:
- Only works with a positive number in the shift parameter.
- Only works with shift less than 26.
- Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
- Does a cast number to character, so it will fail with anything but ascii letters.
- Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
- Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.
Pseudocode:
- Loop through each character in the string.
- Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
- If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
- Append the character onto a new string. Return the string.
Function:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc
Below code handles upper and lower cases as well and leaves other character as it is.
import java.util.Scanner;
public class CaesarCipher
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int length = Integer.parseInt(in.nextLine());
String str = in.nextLine();
int k = Integer.parseInt(in.nextLine());
k = k % 26;
System.out.println(encrypt(str, length, k));
in.close();
}
private static String encrypt(String str, int length, int shift)
{
StringBuilder strBuilder = new StringBuilder();
char c;
for (int i = 0; i < length; i++)
{
c = str.charAt(i);
// if c is letter ONLY then shift them, else directly add it
if (Character.isLetter(c))
{
c = (char) (str.charAt(i) + shift);
// System.out.println(c);
// checking case or range check is important, just if (c > 'z'
// || c > 'Z')
// will not work
if ((Character.isLowerCase(str.charAt(i)) && c > 'z')
|| (Character.isUpperCase(str.charAt(i)) && c > 'Z'))
c = (char) (str.charAt(i) - (26 - shift));
}
strBuilder.append(c);
}
return strBuilder.toString();
}
}