-3

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" };
4

2 回答 2

2

使用Random类:

string[] arr1 = new string[] { "one", "two", "three" };
var idx = new Random().Next(arr1.Length);
return arr1[idx];
于 2013-07-24T00:13:07.917 回答
2
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

于 2013-07-24T00:14:15.503 回答