从字符串数组中检索随机单词

时间:2013-07-24 00:10:35

标签: c#

我有一个包含5个不同单词的字符串数组。如何随机选择一个并将其存储在字符串变量中?

string[] arr1 = new string[] { "one", "two", "three" };

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用Random类:

string[] arr1 = new string[] { "one", "two", "three" };
var idx = new Random().Next(arr1.Length);
return arr1[idx];
相关问题