Ad space (banner)
#๏ธโƒฃC# 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 C#, and understand the basic idea of encrypting by shifting characters. This is for anyone searching for "C# 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 builds the result with a StringBuilder, checks whether each character is in the alphabet, and computes the shifted letter with (c - 'A' + shift) % 26 + 'A'. 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 C# 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)