我正在尝试存储表示4位字符串的整数,其中一些开头为0。当我在控制台中写出这些值时,前面的0被剥去了,我可以阻止这种情况发生吗?我通读了文档,但看不到任何阻止此情况发生的内容。到目前为止,这是我的代码:

class Fitness
{
    Random random = new Random();

     int[] myArray = new int[15];
     int[] myArray2 = new int[6];
     int[] numbers = new int[6];
     int randomNumber;
     public void setup()
     {

         for (int i = 0; i < 6; i++)
         {
             do
             {
                 randomNumber = random.Next(1, 16);
             }
             while (numbers.Contains(randomNumber));

             numbers[i] = randomNumber;

         }
         Array.Sort(numbers);
         foreach (int i in numbers)
         {
             Console.WriteLine(i);
         }
         Console.WriteLine("-----------------");
         Console.WriteLine("-----------------");

         myArray[0] = 0001;
         myArray[1] = 0010;
         myArray[2] = 0011;
         myArray[3] = 0100;
         myArray[4] = 0101;
         myArray[5] = 0110;
         myArray[6] = 0111;
         myArray[7] = 1000;
         myArray[8] = 1001;
         myArray[9] = 1010;
         myArray[10] = 1011;
         myArray[11] = 1100;
         myArray[12] = 1101;
         myArray[13] = 1110;
         myArray[14] = 1111;

         for (int i = 0; i < 6; i++)
         {
             myArray2[i] = myArray[numbers[i]-1];
         }
         foreach (int i in myArray2)
         {
             Console.WriteLine(i);
         }
     }
}

最佳答案

尝试

Console.WriteLine(i.ToString("D4"));


阅读有关Standard Numeric Format Strings...的更多信息

这与此问题有关C# convert int to string with padding zeros?

编辑

当您显示上述格式的字符串时,您可以使用int数组执行任何操作。

关于c# - 如何在C#中停止从我的整数中删除前导0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16059056/

10-11 12:44