[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Generate random strings in C#

generate random strings

Sometimes it's useful to generate random strings, often to test a program such as one that sorts strings.

The Random class's Next method generates random numbers. To make random words, you can make an array of letters and 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.

Enter the number of words and the word length and click Go. The following code generates 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); } }

(If you want to make words of random lengths, you can extract the inner for loop into a MakeRandomWord method that takes a length as a parameter. Then call that method with random lengths.)

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.