How to select a random string from an array of strings
This article demonstrates how to pick a random string an array of strings.
We can use the random number generator to pick a random item from an array. The following code snippet has an array of author names (strings). We can pick a random author by generating a random number that is less than the number of items in the array and use the random index to pick a random author name in the string.
The Random.Next method generates a random integer and by passing the maximum length of the array means the random number cannot be greater than the number of items in the array.
- using System;
- public class RandomStringInArraySample
- {
- public static void Main()
- {
-
- string[] authors = { "Mahesh Chand", "Jeff Prosise", "Dave McCarter", "Allen O'neill",
- "Monica Rathbun", "Henry He", "Raj Kumar", "Mark Prime",
- "Rose Tracey", "Mike Crown" };
-
-
- Random rand = new Random();
-
- int index = rand.Next(authors.Length);
-
- Console.WriteLine($"Randomly selected author is {authors[index]}");
-
- Console.ReadKey();
- }
- }
Figure 1
Figure 2
Summary
In this article and code snippet, we discussed how to select a random string fron an array of strings.