提问者:小点点

使用foreach在二维数组中添加空格


我希望生成的代码在每个*之后有一个额外的间隔,但使用foreach方法,但我不确定我做得是否正确

using System;

class MainClass {
  public static void Main (string[] args) {
  char [,] city = new char [10,10];
  int rowLength = city.GetLength(0);
  int colLength = city.GetLength(1);
  string output = "";
  for(int i = 0; i < rowLength; i++){
    for(int j = 0; j < colLength; j++){
      city[i,j] = '*';
      
      foreach (char val in city)
      output+= val+"\t";
      
      Console.Write("{0}",city[i,j]);
    }//end j
    Console.WriteLine();
  }//end i
  Console.WriteLine("done");
}
}

但打印后不会添加标签。是不是摆放错了?


共1个答案

匿名用户

所以我不确定这是您正在寻找的确切解决方案,但是您可以跳过foreach循环,只需将其添加到Write()中。

        class MainClass
        {
            public static void Main(string[] args)
            {
                char[,] city = new char[10, 10];
                int rowLength = city.GetLength(0);
                int colLength = city.GetLength(1);
                string output = "";
                for (int i = 0; i < rowLength; i++)
                {
                    for (int j = 0; j < colLength; j++)
                    {
                        city[i, j] = '*';
        
                        //foreach (char val in city)
                            //output += val + "\t";
        
                        Console.Write("{0}", city[i, j] + "\t");
                    }//end j
                    Console.WriteLine();
                }//end i
                Console.WriteLine("done");
            }
        }