Search code examples
vb.nettextboxtranslationletter

How to check a text box for a certain character and replace with a different string in the same spot


I am working on a little morse code translation project and I cannot figure out how to detect when a certain key is in a textbox and replace it with the corresponding morse code dots and dashes in the correct spot.

For example if you type in "a b c" then i would like the program to check and put

".- -... -.-."

but it also needs to be dynamic so if you change up the order of your letters it can update the translation.

as of right now i have a key checking system where you can only type in one forward line and if you mess up you have to clear the whole box. thank you!


Solution

  • Here is a basic example of what I was suggesting in my comments above, i.e. using two separate TextBoxes and translating the whole text every time:

    Private morseCodeDictionary As New Dictionary(Of Char, String) From {{"a"c, ".-"},
                                                                         {"b"c, "-..."},
                                                                         {"c"c, "-.-."}}
    
    Private Sub inputTextBox_TextChanged(sender As Object, e As EventArgs) Handles inputTextBox.TextChanged
        outputTextBox.Text = String.Join(" ",
                                         inputTextBox.Text.
                                                      ToLower().
                                                      Select(Function(ch) morseCodeDictionary(ch)))
    End Sub
    

    Here's an implementation that doesn't use LINQ, so may be more understandable:

    Private Sub inputTextBox_TextChanged(sender As Object, e As EventArgs) Handles inputTextBox.TextChanged
        Dim characterStrings As New List(Of String)
    
        For Each ch As Char In inputTextBox.Text
            characterStrings.Add(morseCodeDictionary(ch))
        Next
    
        outputTextBox.Text = String.Join(" ", characterStrings)
    End Sub