Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从字符串数组中检索随机词_C# - Fatal编程技术网

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

C# 从字符串数组中检索随机词,c#,C#,我有一个包含5个不同单词的字符串数组。如何随机选择一个并将其存储在字符串变量中 string[] arr1 = new string[] { "one", "two", "three" }; 使用随机类: 这是文档中的一个示例 研究它,它将很容易采用这一点,以满足您的需要。其思想是生成一个随机索引并使用它对数组进行索引 像这样?:。你看过系统吗?随机类?看,应该是1.长度-1@LukeHutton:不,上限是排他性的。但可以是new Random.nextar1.Length。@LukeHut

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

string[] arr1 = new string[] { "one", "two", "three" };
使用随机类:

这是文档中的一个示例

研究它,它将很容易采用这一点,以满足您的需要。其思想是生成一个随机索引并使用它对数组进行索引

像这样?:。你看过系统吗?随机类?看,应该是1.长度-1@LukeHutton:不,上限是排他性的。但可以是new Random.nextar1.Length。@LukeHutton不,它应该是arr1.Lengthdoh,是的,刚刚看到。。。包容性较低,排他性较高为什么会被否决?我没有也不会否决这个答案,但我怀疑这是为了给OP一条众所周知的鱼,而不是教他钓鱼。嗯。。我试图鼓励OP使用链接和示例来了解更多关于该主题的信息。当人们开始编程时,索引间接的解决方案并不总是显而易见的:-
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]);
   }
}