I have a string array containing 5 different words. How can I randomly pick one and store it in a string variable?
string[] arr1 = new string[] { "one", "two", "three" };
I have a string array containing 5 different words. How can I randomly pick one and store it in a string variable?
string[] arr1 = new string[] { "one", "two", "three" };
使用Random
类:
string[] arr1 = new string[] { "one", "two", "three" };
var idx = new Random().Next(arr1.Length);
return arr1[idx];
using System;
public class Example
{
public static void Main()
{
Random rnd = new Random();
string[] malePetNames = { "Rufus", "Bear", "Dakota", "Fido",
"Vanya", "Samuel", "Koani", "Volodya",
"Prince", "Yiska" };
string[] femalePetNames = { "Maggie", "Penny", "Saya", "Princess",
"Abby", "Laila", "Sadie", "Olivia",
"Starlight", "Talla" };
// Generate random indexes for pet names.
int mIndex = rnd.Next(malePetNames.Length);
int fIndex = rnd.Next(femalePetNames.Length);
// Display the result.
Console.WriteLine("Suggested pet name of the day: ");
Console.WriteLine(" For a male: {0}", malePetNames[mIndex]);
Console.WriteLine(" For a female: {0}", femalePetNames[fIndex]);
}
}
这是文档中的一个示例。
研究它,很容易采用它来满足您的需求。这个想法是生成一个随机索引并使用它来索引数组 http://msdn.microsoft.com/en-us/library/system.random.aspx