如何水平打印数组的内容?

为什么控制台窗口不是水平地而是垂直地打印数组内容?

有没有办法改变这个?

如何显示我的数组的内容而不是垂直,与Console.WriteLine()

例如:

 int[] numbers = new int[100] for(int i; i < 100; i++) { numbers[i] = i; } for (int i; i < 100; i++) { Console.WriteLine(numbers[i]); } 

您可能正在使用Console.WriteLine打印数组。

 int[] array = new int[] { 1, 2, 3 }; foreach(var item in array) { Console.WriteLine(item.ToString()); } 

如果您不想让每个项目在单独的行上使用Console.Write

 int[] array = new int[] { 1, 2, 3 }; foreach(var item in array) { Console.Write(item.ToString()); } 

string.Join<T> (在.NET Framework 4或更高版本中):

 int[] array = new int[] { 1, 2, 3 }; Console.WriteLine(string.Join(",", array)); 

我会build议 :

 foreach(var item in array) Console.Write("{0}", item); 

如上所述,除非一个项目为null ,否则不会引发exception。

 Console.Write(string.Join(" ", array)); 

将是完美的,如果数组是一个string[]

只需循环访问数组,然后使用Write而不是WriteLine将项目写入控制台:

 foreach(var item in array) Console.Write(item.ToString() + " "); 

只要你的物品没有任何换行符,就会产生一个单行。

…或者,正如Jon Skeet所说,为你的问题提供更多的背景。

 foreach(var item in array) Console.Write(item.ToString() + "\t"); 
  public static void Main(string[] args) { int[] numbers = new int[10]; Console.Write("index "); for (int i = 0; i < numbers.Length; i++) { numbers[i] = i; Console.Write(numbers[i] + " "); } Console.WriteLine(""); Console.WriteLine(""); Console.Write("value "); for (int i = 0; i < numbers.Length; i++) { numbers[i] = numbers.Length - i; Console.Write(numbers[i] + " "); } Console.ReadKey(); } } } 
 int[] n=new int[5]; for (int i = 0; i < 5; i++) { n[i] = i + 100; } foreach (int j in n) { int i = j - 100; Console.WriteLine("Element [{0}]={1}", i, j); i++; } 

如果你需要漂亮的打印数组的数组可以这样工作http://aaron-hoffman.blogspot.com/2013/11/pretty-print-array-of-arrays-in-net-c.html

 public string PrettyPrintArrayOfArrays(int[][] arrayOfArrays) { if (arrayOfArrays == null) return ""; var prettyArrays = new string[arrayOfArrays.Length]; for (int i = 0; i < arrayOfArrays.Length; i++) { prettyArrays[i] = "[" + String.Join(",", arrayOfArrays[i]) + "]"; } return "[" + String.Join(",", prettyArrays) + "]"; } 

输出示例:

 [[2,3]] [[2,3],[5,4,3]] [[2,3],[5,4,3],[8,9]] 
 namespace ReverseString { class Program { static void Main(string[] args) { string stat = "This is an example of code" + "This code has written in C#\n\n"; Console.Write(stat); char[] myArrayofChar = stat.ToCharArray(); Array.Reverse(myArrayofChar); foreach (char myNewChar in myArrayofChar) Console.Write(myNewChar); // Yuo just need to write the function Write instead of WriteLine Console.ReadKey(); } } } 

这是输出

 #C ni nettirw sah edoc sihTedoc fo elpmaxe na si sihT 
 private int[,] MirrorH(int[,] matrix) //the method will return mirror horizintal of matrix { int[,] MirrorHorizintal = new int[4, 4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j ++) { MirrorHorizintal[i, j] = matrix[i, 3 - j]; } } return MirrorHorizintal; }