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

本文关键字:随机 选择 字符串 | 更新日期: 2023-09-27 18:04:51

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

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方法中的随机值,我将获得相应的单词(因为列表是按顺序排列的)

如果选择了' yellow '则对应的西班牙语应该是'lo'

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

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

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;
    }
}

变化:

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

string randomword = EnglishWords[index];

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

你应该改变

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

  string randomword = EnglishWords[index];