Search code examples
javacryptographycaesar-cipher

Caesar Cipher With Space characters left unchanged


I'm trying to let the encryption function ignore the white spaces and the symbols between words from the UserInput. Should I use isWhitespace or what? and how to implement that?

The output for this program is totally correct, it shifts each letter to the next 7 one. but it doesn't accept shifting 2 words separated by space or coma.

I'm new into Java stunning world & I'm really enjoying it! Hence this's my 3rd week since I began.

import java.util.Scanner;

public class Test_Cipher{
    public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

    public static String encrypt(String plainText, int shiftKey) {
        plainText = plainText.toLowerCase();
        String cipherText = "";
        for (int i = 0; i < plainText.length(); i++) {
            int charPosition = ALPHABET.indexOf(plainText.charAt(i));
            int keyVal = (shiftKey + charPosition) % 26;
            char replaceVal = ALPHABET.charAt(keyVal);
            cipherText += replaceVal;
        }
        return cipherText;
    }
}

Solution

  • There is two ways of doing this: either create a positive match for the character or a negative one. In the positive match variant you first check if plainText.charAt(i) is a character that you want to keep, and in that case add it to the cipherText and continue with the loop.

    In the other you can check if indexOf returns -1 indicating that the alphabet doesn't contain the character. In that case you do the same thing: add it and continue. This is the common method I've seen for the classic Ceasar "play" cipher:

    // introduce a local variable, you don't want to perform charAt twice
    char c = plainText.charAt(i);
    int charPosition = ALPHABET.indexOf(c);
    // if charPositions is -1 then it is not found 
    if (charPosition == -1) { // or define a constant NOT_FOUND = -1
        cipherText += c;
        // continue with the for loop
        continue;
    }