![](/img/trans.png)
[英]Replacing specific numbers with String.Replace or Regex.Replace
[英]Replacing numbers into specific string
我应该生成随机数字,然后给出数字,但使用不同的名称。
我设法创建了随机数,但是我坚持给出正确的输出:
我的代码:
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);
}
}
如您所见,我尝试将数组转换为String,然后将每个数字替换为X。
输入:5个随机数输出:
此输出是正确的,但下一个输出应如下所示:
我也尝试过使用Regex Regex r = new Regex("[0-9]"", RegexOptions.None);
第一个错误是
string result = array.ToString();
应该
string result = item.ToString();
这是一种解决方案:
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
“如果我想像0:XX这样输出它,那么前面的数组编号又该怎么办?”
这应该工作:
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);
}
您正在用“ X”替换1。 您应该使用这些值来添加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.