All pastes #290364 Raw Edit

Miscellany

public text v1 · immutable
#290364 ·published 2006-12-23 23:09 UTC
rendered paste body
using System;
using System.Collections.Generic;
using System.Text;

namespace caesar_ciqher
{
    class ccipher
    {
        static void Main(string[] args)
        {
            string text, ec;
            int n;
            do
            {
                Console.Write("Encrypt, Decrypt, or Quit?: ");
                ec = Console.ReadLine();
                ec = ec.ToLower();
            } while (!(String.Equals(ec, "d") || String.Equals(ec, "e") || String.Equals(ec, "q")));
            if (String.Equals(ec,"d"))
            {
                Console.Write("Enter cipher text: ");
                text = Console.ReadLine();
                Console.Write("Enter # of characters to move: ");
                n = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Plain text: {0}", crypt(text, n, false));
            }
            else if (String.Equals(ec, "e"))
            {
                Console.Write("Enter plain text: ");
                text = Console.ReadLine();
                Console.Write("Enter # of characters to move: ");
                n = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Cipher text: {0}", crypt(text, n, true));
            }
            else
            {
                Console.WriteLine("Bye!");
                return;
            }
        }

        static string crypt(string text, int n, bool encrypt)
        {
            string alpha = "abcdefghijklmnopqrstuvwxyz";
            StringBuilder omega = new StringBuilder();
            text = text.ToLower();

            for (int i = 0; i < text.Length; i++)
            {
                for (int j = 0; j < alpha.Length; j++)
                {
                    if (String.Compare(text, i, alpha, j, 1) == 0)
                    {
                        if (!encrypt)
                        {
                            if (j - n < 0)
                            {
                                omega.Append(alpha, alpha.Length + (j - n), 1);
                            }
                            else
                            {
                                omega.Append(alpha, j - n, 1);
                            }

                        }
                        else
                        {
                            if (j + n > 25)
                            {
                                omega.Append(alpha, (j + n) - alpha.Length, 1);
                            }
                            else
                            {
                                omega.Append(alpha, j + n, 1);
                            }
                        }
                    }
                }
            }

            return omega.ToString();
        }
    }
}