How can I print the contents of an array horizontally?
Why doesn't the console window print the array contents horizontally rather than vertically?
Is there a way to change that?
How can I display the content of my array horizontally instead of vertically, with a Console.WriteLine()
?
For example:
int[] numbers = new int[100]
for(int i; i < 100; i++)
{
numbers[i] = i;
}
for (int i; i < 100; i++)
{
Console.WriteLine(numbers[i]);
}
Solution 1:
You are probably using Console.WriteLine
for printing the array.
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.WriteLine(item.ToString());
}
If you don't want to have every item on a separate line use Console.Write
:
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.Write(item.ToString());
}
or string.Join<T>
(in .NET Framework 4 or later):
int[] array = new int[] { 1, 2, 3 };
Console.WriteLine(string.Join(",", array));
Solution 2:
I would suggest:
foreach(var item in array)
Console.Write("{0}", item);
As written above, except it does not raise an exception if one item is null
.
Console.Write(string.Join(" ", array));
would be perfect if the array is a string[]
.
Solution 3:
Just loop through the array and write the items to the console using Write
instead of WriteLine
:
foreach(var item in array)
Console.Write(item.ToString() + " ");
As long as your items don't have any line breaks, that will produce a single line.
...or, as Jon Skeet said, provide a little more context to your question.
Solution 4:
If you need to pretty print an array of arrays, something like this could work: Pretty Print Array of Arrays in .NET C#
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) + "]";
}
Example Output:
[[2,3]]
[[2,3],[5,4,3]]
[[2,3],[5,4,3],[8,9]]