Skip to content

Instantly share code, notes, and snippets.

@mikedugan
Created January 4, 2014 00:42
Show Gist options
  • Save mikedugan/8249783 to your computer and use it in GitHub Desktop.
Save mikedugan/8249783 to your computer and use it in GitHub Desktop.
the caesar cipher transforms the string by replacing it with the value at offset n from the char in the string array. nifty.
static string Caesar(string value, int shift)
{
char[] buffer = value.ToCharArray();
for (int i = 0; i < buffer.Length; i++)
{
// Letter.
char letter = buffer[i];
// Add shift to all.
letter = (char)(letter + shift);
// Subtract 26 on overflow.
// Add 26 on underflow.
if (letter > 'z')
{
letter = (char)(letter - 26);
}
else if (letter < 'a')
{
letter = (char)(letter + 26);
}
// Store.
buffer[i] = letter;
}
return new string(buffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment