[英]Replacing numbers into specific string
I'm supposed to generate random numebers and then giveout the numbers but with different name. 我应该生成随机数字,然后给出数字,但使用不同的名称。
I managed to create random numbers, but I stuck at the giving the right output: 我设法创建了随机数,但是我坚持给出正确的输出:
My code: 我的代码:
static Random rnd = new Random();
public static int GetZufall()
{
int random = rnd.Next(0, 10); // from 0 to 9
return random;
}
static void Main(string[] args)
{
Console.WriteLine("How many random numbers do you want: ");
int input = int.Parse(Console.ReadLine());
Console.WriteLine();
int[] array = new int[10];
for (int i = 0; i < input; i++)
{
array[GetZufall()]++;
//Console.WriteLine(GetZufall()); // Random numbers
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"{i} : {array[i]}");
}
int maxValue = array.Max(); // Linq
Console.WriteLine();
Console.WriteLine("Most common value: " + maxValue);
foreach (var item in array)
{
string result = array.ToString();
result = result.Replace("1", "X");
Console.WriteLine(result);
}
}
So as you can see I've tried to convert the array to String and then replace each number with X. 如您所见,我尝试将数组转换为String,然后将每个数字替换为X。
Input: 5 random numbers Output: 输入:5个随机数输出:
This output is right, but the next one should be like this: 此输出是正确的,但下一个输出应如下所示:
I've tried also using Regex Regex r = new Regex("[0-9]"", RegexOptions.None);
我也尝试过使用Regex
Regex r = new Regex("[0-9]"", RegexOptions.None);
First mistake is 第一个错误是
string result = array.ToString();
should be 应该
string result = item.ToString();
Here's one solution: 这是一种解决方案:
foreach (var item in array)
{
string result = "";
if (item == 0)
result = "0";
else
for (int i = 0; i < item; i++)
result += "X";
Console.WriteLine(result);
}
UPDATE UPDATE
"If I would like to output it like 0 : XX , also the numbers of array in the front what should I do ?" “如果我想像0:XX这样输出它,那么前面的数组编号又该怎么办?”
This should work: 这应该工作:
int count = 0;
foreach (var item in array)
{
string result = "";
result = count.ToString() + " : ";
count++;
for (int i = 0; i < item; i++)
result += "X";
Console.WriteLine(result);
}
You are replacing 1s with 'X'. 您正在用“ X”替换1。 You should use the values to add Xs like this:
您应该使用这些值来添加X,如下所示:
foreach (int x in array)
{
result = "";
for (i = 0; i < x; i++)
result += "X"
if (result == "")
result = "0";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.