Strings in Visual Basic

Start a new project named Anagrams. Build the form as shown below:

  1. There is a labellabel with the words "Enter a word and press enter:"
  2. There is a text box textboxnamed TxtWord.
  3. There is a labellabel named LblAnagram


4. Write the code as shown below:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Randomize() 'This make sure it is different each time you run it
    End Sub

    Sub Shuffle(ByVal ParamArray letters As String()) 'The array is passed by reference
        Dim I, P As Integer
        Dim Temp As Char
        For I = 0 To letters.Length - 1
            P = Rnd() Mod letters.Length 'Pick a random letter
            Temp = letters(I)  'Swap letter(P) and Letter(i)
            letters(I) = letters(P)
            letters(P) = Temp
    End Sub 'Shuffle

    Function SplitString(ByVal word As String) As String() 'Change a string to an array of strings
        Dim I As Integer
        Dim Letters As String()
        ReDim Letters(word.Length - 1) 'Make the size of Letters big enough for each letter in word
        For I = 0 To word.Length - 1 'Loop through each letter and put in the array
            letters(I) = word.Substring(I, 1)
        Return Letters 'returns a String Array
    End Function 'SplitString

    Function Compress(ByVal ParamArray letters As String()) As String
        Dim I As Integer
        Dim S As String = "" 'Start with an empty string and cancatenate each letter to it
        For I = 0 To letters.Length - 1
            S = S & letters(I)
        Return S 'Return the String made from the Array
    End Function 'Compress
    Private Sub TxtWord_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtWord.KeyPress
        If e.KeyChar.Equals(Chr(13)) Then 'If they pressed Enter
            Dim Letters As String()
            Dim word As String = TxtWord.Text 'Get the word they typed in
            Letters = SplitString(word) 'Turn the word into an array of Letters
            Shuffle(Letters) 'Scramble the letters
            LblAnagram.Text = Compress(Letters) 'Put it back into a string and display it
        End If
    End Sub
End Class
Experiment: Use a loop to create 10 anagrams and add them to a list box.

NEXT: Cryptograms