Recipe 5.34. Converting a String to Morse Code

Problem

You want to convert a text string to Morse code characters.

Solution

Sample code folder: Chapter 05\MorseCode

Use the IndexOf() string method to look up and cross-reference characters to string array entries representing each Morse code character.

Discussion

The following code converts the string "Hello world!" to a string that displays the Morse code "dahs" and "dits" for each character:

` Dim source As String = "Hello world!" Dim characters As String = _    "~ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,:?'-/""" Dim morse( ) As String = { _ "?", ".-", "-…", "-.-.", "-..", ".", "..-.", "--.", "….", _ "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", _ "--.-", ".-.", "…", "-", "..-", "…-", ".--", "-..-", _ "-.--", "--..", "-----", ".----", "..---", "…--", _ "….-", "…..", "-….", "--…", "---..", "----.", _ ".-.-.-", "--..--", "---…", "..--..", ".----.", _ "-….-", "-..-.", ".-..-."} Dim result As New System.Text.StringBuilder Dim counter As Integer Dim position As Integer For counter = 0 To source.Length - 1    position = characters.IndexOf(Char.ToUpper( _       source.Chars(counter)))    If (position < 0) Then position = 0    result.Append(source.Substring(counter, 1))    result.Append(Space(5))    result.AppendLine(morse(position)) Next counter MsgBox(result.ToString( )) `

For most people this code is not all that useful, but there are some interesting details to be learned from this example. For instance, the second line assigns the standard set of characters covered by Morse code to a string named characters. Notice that at the tail end of this string there are three quote characters in a row. The last one terminates the string, as expected, and the pair just before the last one demonstrates how to enter a single-quote character into a string. By doubling up the quote character, you tell the Visual Basic compiler to enter one double-quote character and not to terminate the string.

At the head of the characters string is a tilde (~) character. This is not a Morse code character, but it provides a way to catch all characters in the string to be converted that aren't found in the set of Morse code characters. For example, in the test string "Hello world!" there's an exclamation point, which is not defined in the table of International Morse code characters. When the IndexOf() method attempts to find this exclamation point in characters, a value of1 is returned. This value is changed to zero, which indexes to the question-mark sequence in the Morse() string array. Figure 5-38 shows how the sample string ends up with a question mark instead of the unavailable exclamation point.

Figure 5-38. The Morse code equivalent of the standard "Hello World!" string

Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon