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

本文关键字:随机 单词 检索 字符串 数组 | 更新日期: 2023-09-27 18:24:49

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

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