【问题标题】:Methode random character in C# [duplicate]C#中的Methode随机字符[重复]
【发布时间】:2018-04-03 01:21:48
【问题描述】:

我应该从字符串 txt "jvn" 中,只获取 1 个随机字符,但由于某种原因,它无法正常工作,我还尝试在循环后将我的字符再次转换为字符串,但它不起作用,我没有返回值

static char Zufallszeichen(string s)
{

    Random rnd = new Random();
    string x = "jvn";

    string result = "";
    Convert.ToChar(x);

    for (int i = 0; i < 1; i++)
    {
        result += x.Substring(rnd.Next(0, x.Length), 1);

    }

    return x;
}

【问题讨论】:

  • 你想做什么?
  • “它不会工作”是什么意思?
  • 你也没有对Convert.ToChar(x)的返回值做任何事情。
  • return x[rnd.Next(0, x.Length)]?
  • 嗯,你想要一个字符串还是一个字符?

标签: c#


【解决方案1】:

我假设您想从输入字符串中获取随机字符,对吧?

首先要做的事情: 您似乎对 C# 或一般编程相当陌生。也许你想要一些tutorials。或者你可以拿一本好的编程书。

尽管如此,让我们来看看这个:

static char Zufallszeichen(string s) /* You never use the argument, why do you have one* */
    {

        Random rnd = new Random();
        string x = "jvn"; // You are creating this string and returning it unchanged at the end

        string result = "";
        Convert.ToChar(x); // This ->returns<- the input as char... so basicly you have to catch the value. But why would you that in the first place

        for (int i = 0; i < 1; i++) // You're looping for 1 iteration (i.e. running the code inside once)
        {
            result += x.Substring(rnd.Next(0, x.Length), 1); // You're appending a random character to the result _string_ but never returning it.

        }

        return x; // You will only return jvn, as x has remained unchanged.
    }

这里有一个非常简单的方法:

public static char GetRandomCharacterFromString(string input)
{
    // Do some basic null-checking
    if(input == null)
    {
        return char.MinValue; // Or throw an exception or, or, or...
    }

    var random = new Random();
    var inputAsCharArray = input.ToCharArray();
    var index = random.Next(0, input.Length);

    return inputAsCharArray[index];
}

编辑:我知道有更简单或更简单的答案,但我希望这种方法更“易于理解”。

【讨论】:

  • 不需要var inputAsCharArray = input.ToCharArray();,使用input[index]已经返回char
  • 谢谢我要去上学,我们正在一步一步做,但是谢谢我会检查教程:)
【解决方案2】:

跟随为我工作的代码:

static char randomLetter(string s)
    {

        Random rnd = new Random();
        int index = rnd.Next (0, s.Length);
        return s[index];
    }
char leter = randomLetter ("abcdef");

【讨论】:

  • 不需要Convert.ToChars[index]已经返回了char
  • 谢谢,我刚刚编辑了答案。
  • 您应该将new Random() 移到方法之外以避免您从快速调用new Random() 获得相同值的情况。
猜你喜欢
  • 1970-01-01
  • 2013-11-12
  • 2020-05-13
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
相关资源
最近更新 更多