Generate random strings in C#

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 void btnGo_Click(object sender, EventArgs e)
{
    lstWords.Items.Clear();

    // Get the number of words and letters per word.
    int num_letters = int.Parse(txtNumLetters.Text);
    int num_words = int.Parse(txtNumWords.Text);

    // Make an array of the letters we will use.
    char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

    // Make a random number generator.
    Random rand = new Random();

    // Make the words.
    for (int i = 1; i <= num_words; i++)
    {
        // Make a word.
        string word = "";
        for (int j = 1; j <= num_letters; j++)
        {
            // Pick a random number between 0 and 25
            // to select a letter from the letters array.
            int letter_num = rand.Next(0, letters.Length - 1);

            // Append the letter.
            word += letters[letter_num];
        }

        // Add the word to the list.
        lstWords.Items.Add(word);
    }
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.