Ceasar Cipher (Rot 13) I've created a basic cipher program that will turn your string into a Rot13 cipher. I'm pretty sure there are much easier ways to do this, so a little input on what I've done would be great:


What did I do well?
What can be done better?
Are there easier ways to do this?




using System;

namespace Rot13
{
    class CeasarCipher
    {
        static string Encrypt(string toEncrypt, int shift)
        {
            char[] buffer = toEncrypt.ToCharArray();

            for (int i = 0; i &lt; buffer.Length; i++)
            {
                char letter = buffer[i];
                letter = (char)(letter + shift);

                if (letter &gt; 'z')
                {
                    letter = (char)(letter - 26);
                }
                else if (letter &lt; 'a')
                {
                    letter = (char)(letter + 26);
                }
                buffer[i] = letter;
            }
            return new string(buffer);
        }

        static void Main(string[] args)
        {
            Console.Write("Enter string to cipher: ");
            var toCipher = Console.ReadLine();

            Console.WriteLine(Encrypt(toCipher, 13));
        }
    }
}
You could use the modulo operator instead of conditions:

static string Encrypt(string toEncrypt, int shift)
{
    const int alphabetLength = 'z' - 'a' + 1;
    char[] buffer = toEncrypt.ToCharArray();

    for (int i = 0; i &lt; buffer.Length; i++)
    {
        char letter = (char)(buffer[i] - 'a'); // Let the `letter` be an offset from 'a'
        letter = (char)((letter + shift) % alphabetLength);
        buffer[i] = (char)(letter + 'a');
    }
    return new string(buffer);
}


Or almost one-liner:

static string Encrypt(string toEncrypt, int shift)
{
    const int alphabetLength = 'z' - 'a' + 1;
    return new string(Array.ConvertAll(toEncrypt.ToCharArray(), 
        c =&gt; (char)('a' + (c - 'a' + shift) % alphabetLength)));
}