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

时间:2010-09-13 12:42:01

标签: c# .net arrays

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

有没有办法改变它?

如何使用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]);
}

12 个答案:

答案 0 :(得分:117)

您可能正在使用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));

答案 1 :(得分:27)

我建议:

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

如上所述,除非一项是null,否则不会引发异常。

Console.Write(string.Join(" ", array));
如果数组是string[]

将是完美的

答案 2 :(得分:18)

只需循环遍历数组,然后使用Write代替WriteLine将项目写入控制台:

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

只要您的商品没有任何换行符,就会生成一行。

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

答案 3 :(得分:3)

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

答案 4 :(得分:2)

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

答案 5 :(得分:1)

如果你需要漂亮地打印一个像这样的数组,这可能会起作用 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]]

答案 6 :(得分: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++;
}

答案 7 :(得分: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();
        }
    }
}

答案 8 :(得分:0)

使用Console.Write仅在线程是写入控制台的唯一线程时才有效,否则您的输出可能会散布其他输出,这些输出可能会也可能不会插入换行符,以及其他不需要的字符。要确保完整打印数组,请使用Console.WriteLine编写一个字符串。大多数任何对象数组都可以使用.NET 4.0之前的非泛型连接水平打印(取决于类型的ToString()方法):

        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>()));

答案 9 :(得分:0)

下面的解决方案是最简单的

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

输出:[1, 2, 3, 4, 5]

另一个简短的解决方案

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

输出:1 2 3 4 5,或者如果您需要在下面添加添加,,请使用

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

输出:1, 2, 3, 4, 5

答案 10 :(得分:0)

我已经写了一些扩展名以适应几乎所有需求。
使用分隔符 String.Format IFormatProvider 的扩展过载。

示例:

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();

扩展名:

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);
        }
    }
}

答案 11 :(得分:-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;
}