Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 34 / 68

Building a Caesar Cipher (a Character-Shifting Cipher)

In this lesson you will learn how to implement a Caesar cipher in Kotlin, and understand the basic idea of encrypting by shifting characters. This is for anyone searching for "Kotlin Caesar cipher implementation".

The Caesar cipher is a simple cipher from ancient Rome that replaces each letter with the one a fixed number of positions further along the alphabet. It is the same idea as a childhood game of shifting every letter by three.

The sample code processes one character at a time with text.map { c -> ... }, checks whether it is in the alphabet with c in 'A'..'Z', and computes the shifted letter with 'A' + (c - 'A' + shift) % 26. Notice how anything that is not a letter is passed through unchanged.

A common stumbling block for beginners is the character-code arithmetic. You need % 26 to handle the case where the shifted result runs past the end of the alphabet (A to Z).

It is simple compared with modern cryptography, but it is an ideal introductory exercise for practising character-code arithmetic.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)