C# C语言中的随机字符方法#
我应该从字符串txt“jvn”中得到1个随机字符,但由于某些原因,它不起作用。我还在循环后尝试将我的字符再次转换为字符串,但它不起作用,我没有返回值C# C语言中的随机字符方法#,c#,C#,我应该从字符串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++
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;
}
静态字符Zufallszeichen(字符串s)
{
随机rnd=新随机();
字符串x=“jvn”;
字符串结果=”;
转换为ToChar(x);
对于(int i=0;i<1;i++)
{
结果+=x.子字符串(rnd.Next(0,x.长度),1);
}
返回x;
}
我假设您想从输入字符串中获取一个随机字符,对吗
第一件事:
您似乎对C#或一般编程相当陌生。也许你想要一些。或者你也可以买一本好的编程书
尽管如此,我们还是要经历一下:
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.
}
编辑:我知道有更容易或更简单的答案,但我希望这种方法更“易懂”。以下代码对我有用:
static char randomLetter(string s)
{
Random rnd = new Random();
int index = rnd.Next (0, s.Length);
return s[index];
}
char leter = randomLetter ("abcdef");
你想做什么?什么是“它不起作用”呢?你也没有用
Convert.ToChar(x)
return x[rnd.Next(0,x.Length)]
?你想要字符串还是字符?不需要var-inputashararay=input.tocharray()
,使用input[index]
已经返回了一个char
谢谢我要去上学,我们正在一步一步地做,但是谢谢我会检查教程:)没有必要转换。ToChar,s[index]
已经返回了一个char
谢谢,我刚刚编辑了答案。你应该移动新的随机()
到方法之外,以避免快速调用new Random()
时获得相同值的情况。
static char randomLetter(string s)
{
Random rnd = new Random();
int index = rnd.Next (0, s.Length);
return s[index];
}
char leter = randomLetter ("abcdef");