Created
March 27, 2023 05:47
-
-
Save iomoath/ff2416f658a1b394978aff1735c89adc to your computer and use it in GitHub Desktop.
Morse code encoder & decoder c#
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
using System; | |
using System.Collections.Generic; | |
namespace MorseEncoder | |
{ | |
internal class Program | |
{ | |
private static void Main() | |
{ | |
var text = "welcome to the new age"; | |
var morse = new MorseEncoder(); | |
string morseCode = morse.Encode(text); | |
Console.WriteLine(morseCode); | |
Console.Read(); | |
} | |
} | |
internal class MorseEncoder | |
{ | |
private readonly Dictionary<char, string> _morseCode = new Dictionary<char, string>() | |
{ | |
{'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', "--.."}, | |
{'0', "-----"}, | |
{'1', ".----"}, | |
{'2', "..---"}, | |
{'3', "...--"}, | |
{'4', "....-"}, | |
{'5', "....."}, | |
{'6', "-...."}, | |
{'7', "--..."}, | |
{'8', "---.."}, | |
{'9', "----."}, | |
{'.', ".-.-.-"}, | |
{',', "--..--"}, | |
{'?', "..--.."}, | |
{'\'', ".----."}, | |
{'!', "-.-.--"}, | |
{'/', "-..-."}, | |
{'(', "-.--."}, | |
{')', "-.--.-"}, | |
{'&', ".-..."}, | |
{':', "---..."}, | |
{';', "-.-.-."}, | |
{'=', "-...-"}, | |
{'+', ".-.-."}, | |
{'-', "-....-"}, | |
{'_', "..--.-"}, | |
{'\"', ".-..-."}, | |
{'$', "...-..-"}, | |
{'@', ".--.-."}, | |
{' ', "/"} | |
}; | |
public string Encode(string message) | |
{ | |
message = message.ToUpper(); | |
string encodedMessage = ""; | |
foreach (char character in message) | |
{ | |
if (_morseCode.ContainsKey(character)) | |
{ | |
encodedMessage += _morseCode[character] + " "; | |
} | |
else | |
{ | |
encodedMessage += character + " "; | |
} | |
} | |
return encodedMessage.Trim(); | |
} | |
public string Decode(string message) | |
{ | |
string[] words = message.Split('/'); | |
string decodedMessage = ""; | |
foreach (string word in words) | |
{ | |
string[] letters = word.Split(' '); | |
foreach (string letter in letters) | |
{ | |
foreach (KeyValuePair<char, string> kvp in _morseCode) | |
{ | |
if (letter == kvp.Value) | |
{ | |
decodedMessage += kvp.Key; | |
break; | |
} | |
} | |
} | |
decodedMessage += " "; | |
} | |
return decodedMessage.Trim(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment