Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add C# implementation of Ceasar Cipher
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using System; | ||
using System.Linq; | ||
|
||
namespace CaesarCipher | ||
{ | ||
class Program | ||
{ | ||
static char Encrypt(char ch, int shift) | ||
{ | ||
if (!char.IsLetter(ch)) return ch; | ||
char offset = char.IsUpper(ch) ? 'A' : 'a'; | ||
return (char)((ch + shift - offset) % 26 + offset); | ||
} | ||
|
||
static string Encrypt(string input, int shift) | ||
{ | ||
return String.Join(String.Empty, input.Select(ch => Encrypt(ch, shift))); | ||
} | ||
|
||
static string Decrypt(string input, int shift) | ||
{ | ||
return Encrypt(input, 26 - shift); | ||
} | ||
|
||
static void Main() | ||
{ | ||
string original = "Hey al-go-rithms! Hello from C#"; | ||
string encrypted = Encrypt(original, 5); | ||
string decrypted = Decrypt(encrypted, 5); | ||
Console.WriteLine($"Original: {original}"); | ||
Console.WriteLine($"Encrypted: {encrypted}"); | ||
Console.WriteLine($"Decrypted: {decrypted}"); | ||
} | ||
} | ||
} |