In this post we will learn how to “select random string from an array in C#”. We have the option to utilize the random number generator to select a random element from given array. The subsequent code snippet contains an array of student’s names (strings). We can select a random student by generating a random number that is smaller than the quantity of elements in the array and utilize the random index to select a random writer name within the string.
So, how to do this? The Random.Next() function produces a random whole number and by specifying the maximum size of the array, ensures that the generated number will not exceed the number of elements in the array.
static void Main(string[] args)
{
//let's create Students Array
string[] students = { "Mukesh", "Ravi", "David", "Peter","Smith", "Henry", "Raj k", "Mark Smith","Tracey", "Thomson" };
// Let's Create a Random number using Random class object
Random rand = new Random();
// Lets Generate a random number which is less than the size of the our array.
int index = rand.Next(students.Length);
Console.WriteLine($"Randomly Selected Student is {students[index]}");
Console.ReadKey();
}
Random String Output:

Hence using above example, we discussed how to select a random string from an array of strings. You can also check same in JavaScript here and can Visit our website’s C# Section for more such information.
Comments are closed.