![](/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.