Caesar Cipher – Java/Kotlin

Overview

In this article we will see how to solve the Caesar Cipher problem mention in Perl Weekly Challenge. You are given string $str containing alphabets A..Z only and a number $n. Write a program to encrypt the given string $str using Caesar Cipher with left shift of size $n.

Figure 1. Caesar Cipher

It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on.

Example

Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Output: XYZABCDEFGHIJKLMNOPQRSTUVW

Code

First lets convert the string to an array of characters so that we can check eash one:

char character : input.toCharArray()

Now we will iterate each character. If the character is a space we will append the character itself in the String Builder:

if (character == ' ') {
    sb.append(character);
    continue;
}

Now calculate the original position of the character in reference to ‘A’:

int originalPosition = character - 'A';

Now we can calculate the new position by shifting the character with the offset then getting the modulus of 26:

int newPosition = (originalPosition - offset) % 26;

If the new position is a positive value then we can get the new character by just adding the new position to ‘A’:

char newCharacter = (char) ('A' + newPosition);

We need to cater for the scenario where the new position is negative. In this case we will add the value to ‘Z’:

if (newPosition < 0) {
    newCharacter = (char) ('Z' + (newPosition + 1));
}
CaesarCipher.java
import java.util.Scanner;

public class CaesarCipher {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a string");
        String str = scanner.nextLine();
        System.out.println("Enter offset");
        int offset = scanner.nextInt();
        System.out.println("Output: "+ caesarCipher(str, offset));
    }

    private static String caesarCipher(String input, int offset) {
        StringBuilder sb = new StringBuilder();
        for (char character : input.toCharArray()) {
            if (character == ' ') {
                sb.append(character);
                continue;
            }
            int originalPosition = character - 'A';
            int newPosition = (originalPosition - offset) % 26;
            char newCharacter = (char) ('A' + newPosition);
            if (newPosition < 0) {
                newCharacter = (char) ('Z' + (newPosition + 1));
            }

            sb.append(newCharacter);
        }
        return sb.toString();
    }
}

Below is the Kotlin solution of the same problem:

CaesarCipher.kt

import java.util.*

object CaesarCipherKotlin {

    @JvmStatic
    fun main(args: Array<String>) {
        val scanner = Scanner(System.`in`);
        println("Enter a string")
        val str = scanner.nextLine()
        println("Enter offset")
        val offset = scanner.nextInt()
        println("Output: " + caesarCipher(str, offset))
    }

    private fun caesarCipher(str: String, offset: Int): String {
        val sb = StringBuilder()
        for(character in str.toCharArray()) {
            if (character == ' ') {
                sb.append(character)
                continue
            }
            val originalPosition = character - 'A'
            val newPosition = (originalPosition - offset) % 26
            var newCharacter = ('A'.toInt() + newPosition).toChar()
            if (newPosition < 0) {
                newCharacter = ('Z'.toInt() + (newPosition + 1)).toChar()
            }
            sb.append(newCharacter)
        }
        return sb.toString();
    }
}

Conclusion

In this article we how to solve the Caesar Cipher problem in Java. Please note that there are other ways to solve the same problem as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: