如何在c#中随机选择一个字符串

时间:2013-03-20 19:45:49

标签: c# arrays string visual-studio-2010

我正在编写一个简单的语言翻译器,它将显示英语单词并询问相应的外语单词。到目前为止,代码将从数组中选择一个随机字,但是我现在正试图让它从列表中选择相应的外来字。这是迄今为止的代码:

public class Words
    {
        public int spanishindex; 
        string[] EnglishWords = { "Yellow", "Yello", "Yelow", "Yllow", "ellow" };
        string[] SpanishWords= { "giallo", "giall", "iallo", "gllo", "lo" };

        public String GetRandomWord()
        {
            Random randomizer = new Random();
            index = randomizer.Next(EnglishWords.Length);
            string randomword = EnglishWords[randomizer.Next(index)];
            spanishindex= index;
            return randomword;
        }

        public String MatchSpanishWord()
        {
            string matchword = SpanishWords[spanishindex];
            return matchword;
        }
    }

我的想法是通过将索引值反对传递给MatchSpanishWord方法中的随机值,我会得到相应的单词(因为列表是有序的)

因此,如果选择'ellow',则西班牙语等效项应为'lo'

任何帮助都将不胜感激,谢谢。

3 个答案:

答案 0 :(得分:3)

问题在于你是随机调用两次:一次生成随机索引,然后再次在数组索引中。我在下面的代码中修正了你的错误:

public class Words
{
    public int spanishindex; 
    string[] EnglishWords = { "Yellow", "Yello", "Yelow", "Yllow", "ellow" };
    string[] SpanishWords= { "giallo", "giall", "iallo", "gllo", "lo" };

    public String GetRandomWord()
    {
        Random randomizer = new Random();
        index = randomizer.Next(EnglishWords.Length);
        string randomword = EnglishWords[index]; //<---- this is the fix
        spanishindex= index;
        return randomword;
    }

    public String MatchSpanishWord()
    {
        string matchword = SpanishWords[spanishindex];
        return matchword;
    }
}

答案 1 :(得分:0)

变化:

string randomword = EnglishWords[randomizer.Next(index)];

string randomword = EnglishWords[index];

...假设您不希望随机索引小于您已经随机找到的索引。

答案 2 :(得分:0)

你应该改变

  string randomword = EnglishWords[randomizer.Next(index)];

  string randomword = EnglishWords[index];
相关问题