This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Algorithms and Data Structures
.NET 2.0+

Convert Text to Morse Code

Morse code is a standard encoding for letters, digits and some other characters that is ideally suited to radio transmissions and is used by amateur radio operators and pilots. This article describes a simple C# class for converting text to Morse code.

Morse Code

Morse code was developed by Samuel Morse and Alfred Vail in 1844 to allow sending of messages using their telegraph machine. Characters were encoded into a series of dots and dashes, which were converted to an electric current via the telegraph. A receiver transformed the electrical impulses into "dot" and "dash" indentations on paper tape that could be decoded manually. Later, the impulses were played as audible tones that could be sent via radio signals. Although modern technology has greatly reduced the requirement for the code, it is still used in aviation and by amateur radio operators.

In this article we will create a class that converts English letters and digits into International Morse code. The code will be represented using full stop (period) characters and hyphens. Individual characters will be separated with spaces and the ends of words will be represented with a slash character. For example, the Morse code for "Morse Code" will appear as:

-- --- .-. ... ./-.-. --- -.. .

This class could be used to encode Morse code before it is played back through the console speaker or sound card, or transmitted using a radio device.

Creating the Project

To begin, create a new console application and add a new class named "MorseConverter".

Initialising the Converter

There is no simple algorithm that can determine the dots and dashes of each Morse code character. Instead, a lookup table will be used. In the code, this lookup table will be stored in a Dictionary, with the letter or digit to be encoded as the key and the Morse code equivalent in the value. To declare the dictionary, add the following line to the MorseConverter class:

Dictionary<char, string> _codes;

We can now initialise the dictionary values in the class's constructor. The following adds all English letters and digits. You could add further characters as desired.

public MorseConverter()
    _codes = new Dictionary<char, string>();
    _codes.Add('A', ".-");
    _codes.Add('B', "-...");
    _codes.Add('C', "-.-.");
    _codes.Add('D', "-..");
    _codes.Add('E', ".");
    _codes.Add('F', "..-.");
    _codes.Add('G', "--.");
    _codes.Add('H', "....");
    _codes.Add('I', "..");
    _codes.Add('J', ".---");
    _codes.Add('K', "-.-");
    _codes.Add('L', ".-..");
    _codes.Add('M', "--");
    _codes.Add('N', "-.");
    _codes.Add('O', "---");
    _codes.Add('P', ".--.");
    _codes.Add('Q', "--.-");
    _codes.Add('R', ".-.");
    _codes.Add('S', "...");
    _codes.Add('T', "-");
    _codes.Add('U', "..-");
    _codes.Add('V', "...-");
    _codes.Add('W', ".--");
    _codes.Add('X', "-..-");
    _codes.Add('Y', "-.--");
    _codes.Add('Z', "--..");
    _codes.Add('1', ".----");
    _codes.Add('2', "..---");
    _codes.Add('3', "...--");
    _codes.Add('4', "....-");
    _codes.Add('5', ".....");
    _codes.Add('6', "-....");
    _codes.Add('7', "--...");
    _codes.Add('8', "---..");
    _codes.Add('9', "----.");
    _codes.Add('0', "-----");

Converting Characters

The conversion of text to Morse code is performed by three methods. At the deepest level, individual characters need to be converted to a series of dots and dashes. This is achieved with the private ConvertCharacter method, which looks up a character in the dictionary and returns the appropriate encoded string. If the character is not present, an empty string is returned. This eliminates punctuation from encoded text without affecting the overall result. Note that this method assumes that the character passed to the 'ch' parameter will be in upper case.

private string ConvertCharacter(char ch)
    if (_codes.Keys.Contains(ch))
        return _codes[ch];
        return string.Empty;

Converting Words

The second method is used to convert entire words to Morse code, using the ConvertCharacter method for each character. A for-each loop processes each character from the string in turn and adds the result to a StringBuilder. The if statement adds a space before all letters except the first, separating the characters for easy readability.

private string ConvertWord(string word)
    StringBuilder sb = new StringBuilder();
    foreach (char ch in word)
        if (sb.Length != 0 && sb[sb.Length - 1] != ' ')
            sb.Append(" ");
    return sb.ToString();

Converting Text

The final method converts a full string of text into Morse code. Firstly, the input text is converted to upper case and is split into words according to the positioning of space characters. The remainder of the code is similar to the ConvertWord method. All words in turn are passed to ConvertWord and the encoded text is combined into the end result. Each word in the result is separated from the next by a forward slash (/).

public string ConvertText(string sentence)
    string[] words = sentence.ToUpper().Split(' ');
    StringBuilder sb = new StringBuilder();
    foreach (string word in words)
        if (sb.Length != 0)
    return sb.ToString();

Testing the Converter

To test the converter, add the following code to the Main method of the console application. Run the program and type words and phrases that you wish to convert. When you press Enter, the Morse code is displayed. To exit the program, press Enter without entering any text.

MorseConverter converter = new MorseConverter();

string toConvert;
    Console.WriteLine("Enter string to convert:");
    toConvert = Console.ReadLine();
    string morse = converter.ConvertText(toConvert);
while (toConvert.Length != 0);
5 April 2010