C#挑选随机字符串

时间:2010-10-19 16:07:30

标签: c#

我基本上只想在由'|'拆分的字符串中选择一个随机值。我找不到一个好的例子,有人有想法吗?

string[] mystrings = ("apple|orange|mayo|fruit|dog"):

string blah = "here i am "+resultsofrandom+" result chosen from mystring was " resultofrandom
很明显,字符串blah只是一个例子,我只是希望从mystrings中随机选择的字符串回到一个新的字符串......

7 个答案:

答案 0 :(得分:15)

string[] mystrings = "apple|orange|mayo|fruit|dog".Split('|');
Random rnd = new Random();
string blah1 = mystrings[rnd.Next(mystrings.Length)];
string blah2 = mystrings[rnd.Next(mystrings.Length)];
string sentence = "here i am " + blah1 + " result chosen from mystring was " + blah2 

答案 1 :(得分:5)

您可以通过拆分字符串来完成此操作:

string[] mystrings = "apple|orange|mayo|fruit|dog".Split('|');

然后使用Random类来选择其中一个字符串:

int choice = new Random().Next(mystrings.Length);

现在你可以把它放在一起:

string blah = "Your selection is: " + mystrings[choice];

答案 2 :(得分:2)

Random rnd= new Random();
        int baseZeroArrayLen = 0;
        string[] mystrings = ("apple|orange|mayo|fruit|dog").Split('|');
        baseZeroArrayLen = mystrings.Length - 1; 
        int randomNumber = rnd.Next(baseZeroArrayLen);
        string rndString = mystrings[randomNumber];

答案 3 :(得分:1)

var mystrings = ("apple|orange|mayo|fruit|dog").Split('|');
string blah = "here i am " + mystrings[new Random().Next(0, mystrings.Length)] + " result chosen..";

我认为它会按预期工作

答案 4 :(得分:1)

这应该这样做:

string[] mystrings = ("apple|orange|mayo|fruit|dog").Split('|');
        Random randomInt = new Random();
            string blah = mystrings[randomInt.Next(mystrings.Length)];

答案 5 :(得分:0)

使用String.Split()拆分分隔字符串并将每个单独的值存储在字符串数组中。然后随机选择一个索引到该数组并显示相应的字符串。

答案 6 :(得分:0)

完全没必要的LINQ替代方案。虽然string.Format在这里可能不错。

string[] mystrings = "apple|orange|mayo|fruit|dog".Split('|');

string blah = string.Format("here i am {0} result chosen from mystring was {0}",
               mystrings.Skip(new Random().Next(mystrings.Length)).First());