Solved Exercise Caesars Cipher Function in C#

Codemastr

CEO
Staff member
Administrator
Feb 1, 2019
36
1
238
Write a Caesars Cipher function in C#

This is the code that solves this requirement:

C#:
/*
 * Author: Codemastr
 * Date: 2019-17-02
 */
using System;
using System.Text; // Needed for StringBuilder()

namespace CesarCipher
{
    class Program
    {
        static void Main(string[] args)
        {
            CCipher Rot = new CCipher();

            Console.WriteLine("Input number to use as key for Cipher:");
            int num = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Input message to cipher:");

            string message = Convert.ToString(Console.ReadLine());
            Console.WriteLine("ENCRYPTED MSG: {0}", Rot.Cipher(message,num));
            Console.ReadKey();
        }
    }
    class CCipher
    {
        public string Cipher(string message, int num)
        {

            char[] uppAlphabet = { 'A', 'B', 'C', 'D' , 'E',
                    'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                    'N','O','P','Q','R','S','T', 'U','V', 'W',
                    'X', 'Y', 'Z' };
            
            char[] lowAlphabet = { 'a', 'b', 'c', 'd' , 'e',
                    'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                    'n','o','p','q','r','s','t', 'u','v', 'w',
                    'x', 'y', 'z' };
            
            char[] messageChar = message.ToCharArray();
            num %= 27; // Fixes any num input
            StringBuilder encrypted = new StringBuilder();
            encrypted.Append("");

            for (int i = 0; i < messageChar.Length; i++)
            {
                if ((int)messageChar[i] == 32)
                    encrypted.Append(" ");
                else
                {
                    for (int j = 0; j < lowAlphabet.Length; j++)
                    {
                        int newChar;
                        if (messageChar[i] == lowAlphabet[j])
                        {
                            newChar = j + num;
                            if (newChar >= lowAlphabet.Length)
                                newChar -= lowAlphabet.Length;
                            encrypted.Append(lowAlphabet[newChar]);
                        }
                        if (messageChar[i] == uppAlphabet[j])
                        {
                            newChar = j + num;
                            if (newChar >= uppAlphabet.Length)
                                newChar -= uppAlphabet.Length;
                            encrypted.Append(uppAlphabet[newChar]);
                        }
                    }
                }
            }
            return encrypted.ToString(); // Return encrypted message
        }
    }
}
This is how it would look:

27


Feel free to ask any question or post a suggestion