|
|
Title | Generate random strings in Visual Basic .NET |
Description | This example shows how to generate random strings in Visual Basic .NET. |
Keywords | random strings, generate strings, random letters, Visual Basic .NET, VB.NET |
Categories | Files and Directories, Software Engineering |
|
|
The Random class's Next method generates random numbers. To make random words, make an array of letters. Then use a Random object to pick one of the letters to add to the word. Repeat until the word is as long as you need.
When you enter the number of words and the word length and click Go, the following code generates the random words and adds them to a ListBox. (In a real program you might want to do something else with the words such as write them into a file or put them in a list or array.)
|
|
' Make the random words.
Private Sub btnGo_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnGo.Click
lstWords.Items.Clear()
' Get the number of words and letters per word.
Dim num_letters As Integer = _
Integer.Parse(txtNumLetters.Text)
Dim num_words As Integer = _
Integer.Parse(txtNumWords.Text)
' Make an array of the letters we will use.
Dim letters() As Char = _
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
' Make a random number generator.
Dim rand As New Random()
' Make the words.
For i As Integer = 1 To num_words
' Make a word.
Dim word As String = ""
For j As Integer = 1 To num_letters
' Pick a random number between 0 and 25
' to select a letter from the letters array.
Dim letter_num As Integer = rand.Next(0, _
letters.Length - 1)
' Append the letter.
word &= letters(letter_num)
Next j
' Add the word to the list.
lstWords.Items.Add(word)
Next i
End Sub
|
|
|
|
|
|