方法C中的随机字符#


Methode random character in C#

本问题已经有最佳答案,请猛点这里访问。

我应该从string txt"jvn"中得到1个随机字符,但是由于某些原因它不起作用,我在循环后尝试再次将char转换为string,但它不起作用,我没有返回值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}


我假设您想从输入字符串中得到一个随机字符,对吗?

首先要做的是:您似乎对C或一般编程还比较陌生。也许你需要一些教程。或者你可以拿一本好的编程书。

尽管如此,让我们来讨论一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.
    }

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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];
}

编辑:我知道有一个更容易或更简单的答案,但我希望这种方法更"可理解"。


以下代码适用于我:

1
2
3
4
5
6
7
8
static char randomLetter(string s)
    {

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