80

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]);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tom
  • 801
  • 1
  • 7
  • 4
  • Have a look at this one as well : http://stackoverflow.com/questions/18033938/system-int32-displaying-instead-of-array-elements/18041923#18041923 – NeverHopeless Aug 04 '13 at 17:36

12 Answers12

137

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));
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
  • 5
    The last example only works for arrays of strings, doesn't it? – Nicola Musatti Feb 05 '14 at 13:30
  • @NicolaMusatti: The last example calls [`String.Join`](http://msdn.microsoft.com/en-us/library/dd992421%28v=vs.100%29.aspx). This method has been introduced in .NET Framework 4 only. – Dirk Vollmar Feb 05 '14 at 13:48
  • Ah, OK. I tried it out on Ideone, but they use a version of Mono that doesn't seem to support it. – Nicola Musatti Feb 05 '14 at 14:54
  • in response to Nicola. any object that implements or overrides ToString() can output it's contents for debugging purposes as it sees fit. handy feature. – JJ_Coder4Hire Aug 21 '14 at 16:49
31

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[].

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Larry
  • 17,605
  • 9
  • 77
  • 106
19

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.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
6

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]]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aaron Hoffman
  • 6,604
  • 8
  • 56
  • 61
5

The below solution is the simplest one:

Console.WriteLine("[{0}]", string.Join(", ", array));

Output: [1, 2, 3, 4, 5]

Another short solution:

Array.ForEach(array,  val => Console.Write("{0} ", val));

Output: 1 2 3 4 5. Or if you need to add add ,, use the below:

int i = 0;
Array.ForEach(array,  val => Console.Write(i == array.Length -1) ? "{0}" : "{0}, ", val));

Output: 1, 2, 3, 4, 5

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ElasticCode
  • 7,311
  • 2
  • 34
  • 45
3
foreach(var item in array)
Console.Write(item.ToString() + "\t");
Nazik
  • 8,696
  • 27
  • 77
  • 123
Mac D'zen
  • 151
  • 11
3
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); // You just need to write the function
                                          // Write instead of WriteLine
            Console.ReadKey();
        }
    }
}

This is the output:

#C ni nettirw sah edoc sihTedoc fo elpmaxe na si sihT
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1
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++;
}
John Odom
  • 1,189
  • 2
  • 20
  • 35
1
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();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jer Har
  • 11
  • 1
0

Using Console.Write only works if the thread is the only thread writing to the Console, otherwise your output may be interspersed with other output that may or may not insert newlines, as well as other undesired characters. To ensure your array is printed intact, use Console.WriteLine to write one string. Most any array of objects can be printed horizontally (depending on the type's ToString() method) using the non-generic Join available before .NET 4.0:

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

        //For clarity
        IEnumerable strings = numbers.Select<int, string>(j=>j.ToString());
        string[] stringArray = strings.ToArray<string>();
        string output = string.Join(", ", stringArray);
        Console.WriteLine(output);

        //OR 

        //For brevity
        Console.WriteLine(string.Join(", ", numbers.Select<int, string>(j => j.ToString()).ToArray<string>()));
G DeMasters
  • 61
  • 1
  • 5
  • 1
    This has nothing to do with the question at hand. OP never even mentioned threads. – MechMK1 Dec 20 '17 at 20:36
  • 1
    This answer has everything to do with the question at hand. It is a one-line, .NET 3.5 compatible solution to the problem using LINQ and the non-generic string.Join method, that also guards against interrupted output from other threads. If you felt my wording of that makes the answer appear heavy on the multi-threading issue, then editing would be far more helpful than declaring a unique and valid solution as irrelevant and down voting it. Down vote if you feel you must, but did you down vote the answers using Console.Write when the OP explicitly asked "...with a Console.WriteLine()?" – G DeMasters Dec 21 '17 at 00:38
0

I have written some extensions to accommodate almost any need.
There are extension overloads to feed with Separator, String.Format and IFormatProvider.

Example:

var array1 = new byte[] { 50, 51, 52, 53 };
var array2 = new double[] { 1.1111, 2.2222, 3.3333 };
var culture = CultureInfo.GetCultureInfo("ja-JP");

Console.WriteLine("Byte Array");
//Normal print 
Console.WriteLine(array1.StringJoin());
//Format to hex values
Console.WriteLine(array1.StringJoin("-", "0x{0:X2}"));
//Comma separated 
Console.WriteLine(array1.StringJoin(", "));
Console.WriteLine();

Console.WriteLine("Double Array");
//Normal print 
Console.WriteLine(array2.StringJoin());
//Format to Japanese culture
Console.WriteLine(array2.StringJoin(culture));
//Format to three decimals 
Console.WriteLine(array2.StringJoin(" ", "{0:F3}"));
//Format to Japanese culture and two decimals
Console.WriteLine(array2.StringJoin(" ", "{0:F2}", culture));
Console.WriteLine();

Console.ReadLine();

Extensions:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Extensions
{
    /// <summary>
    /// IEnumerable Utilities. 
    /// </summary>
    public static partial class IEnumerableUtilities
    {
        /// <summary>
        /// String.Join collection of items using custom Separator, String.Format and FormatProvider. 
        /// </summary>
        public static string StringJoin<T>(this IEnumerable<T> Source)
        {
            return Source.StringJoin(" ", string.Empty, null);
        }

        /// <summary>
        /// String.Join collection of items using custom Separator, String.Format and FormatProvider. 
        /// </summary>
        public static string StrinJoin<T>(this IEnumerable<T> Source, string Separator)
        {
            return Source.StringJoin(Separator, string.Empty, null);
        }

        /// <summary>
        /// String.Join collection of items using custom Separator, String.Format and FormatProvider. 
        /// </summary>
        public static string StringJoin<T>(this IEnumerable<T> Source, string Separator, string StringFormat)
        {
            return Source.StringJoin(Separator, StringFormat, null);
        }

        /// <summary>
        /// String.Join collection of items using custom Separator, String.Format and FormatProvider. 
        /// </summary>
        public static string StringJoin<T>(this IEnumerable<T> Source, string Separator, IFormatProvider FormatProvider)
        {
            return Source.StringJoin(Separator, string.Empty, FormatProvider);
        }

        /// <summary>
        /// String.Join collection of items using custom Separator, String.Format and FormatProvider. 
        /// </summary>
        public static string StringJoin<T>(this IEnumerable<T> Source, IFormatProvider FormatProvider)
        {
            return Source.StringJoin(" ", string.Empty, FormatProvider);
        }

        /// <summary>
        /// String.Join collection of items using custom Separator, String.Format and FormatProvider. 
        /// </summary>
        public static string StringJoin<T>(this IEnumerable<T> Source, string Separator, string StringFormat, IFormatProvider FormatProvider)
        {
            //Validate Source
            if (Source == null)
                return string.Empty;
            else if (Source.Count() == 0)
                return string.Empty;

            //Validate Separator
            if (String.IsNullOrEmpty(Separator))
                Separator = " ";

            //Validate StringFormat
            if (String.IsNullOrWhitespace(StringFormat))
                StringFormat = "{0}";

            //Validate FormatProvider 
            if (FormatProvider == null)
                FormatProvider = CultureInfo.CurrentCulture;

            //Convert items 
            var convertedItems = Source.Select(i => String.Format(FormatProvider, StringFormat, i));

            //Return 
            return String.Join(Separator, convertedItems);
        }
    }
}
Efthymios
  • 253
  • 3
  • 10
-3
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;
}
Danh
  • 5,916
  • 7
  • 30
  • 45