convert text to morse code in csharp

Here is a simple C# method that can be used to convert a string of text to Morse code:

main.cs
public static string TextToMorse(string text)
{
    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', "----."}, {' ', "/"}
    };

    StringBuilder morse = new StringBuilder();
    foreach (char c in text.ToUpper())
    {
        if (morseCode.ContainsKey(c))
        {
            morse.Append(morseCode[c] + " ");
        }
    }

    return morse.ToString();
}
963 chars
25 lines

Here's an example usage:

main.cs
string text = "HELLO WORLD";
string morse = TextToMorse(text);
Console.WriteLine(morse); // prints ".... . .-.. .-.. --- / .-- --- .-. .-.. -.. "
146 chars
4 lines

gistlibby LogSnag