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


77

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

有办法改变吗?

如何使用a而不是垂直显示数组内容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]);
}

Answers:


131

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

5
最后一个示例仅适用于字符串数组,不是吗?
Nicola Musatti 2014年

@NicolaMusatti:最后一个示例调用String.Join<T>。仅在.NET Framework 4中引入了此方法。
德克·沃尔玛2014年

喔好吧。我在Ideone上尝试过,但是他们使用的Mono版本似乎不支持它。
Nicola Musatti 2014年

回应尼古拉。任何实现或重写ToString()的对象都可以根据需要输出其内容用于调试。方便的功能。
JJ_Coder4Hire

30

我会建议:

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

如上所述,但如果一项是,则不会引发例外null

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

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


19

只需遍历数组,然后使用Write而不是将项目写入控制台WriteLine

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

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

...或者,如乔恩·斯基特(Jon Skeet)所说,为您的问题提供了更多背景信息。


5

如果您需要漂亮地打印数组数组,则可以使用以下方法:.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) + "]";
}

示例输出:

[[2,3]]

[[2,3],[5,4,3]]

[[2,3],[5,4,3],[8,9]]

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

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

这是输出:

#C ni nettirw sah edoc sihTedoc fo elpmaxe na si sihT

一个解释将是有条理的。
彼得·莫滕森

2

以下解决方案是最简单的解决方案:

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

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

另一个简短的解决方案:

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

输出:1 2 3 4 5。或者,如果您需要添加add ,,请使用以下命令:

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

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


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

一个解释将是有条理的。
彼得·莫滕森

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

也许告诉OP他做错了什么以及如何解决?
Marthijn 2014年

一个解释将是有条理的。
彼得·莫滕森

0

仅当该线程是唯一写入控制台的线程时,才能使用Console.Write,否则您的输出可能会与可能插入或未插入换行符的其他输出以及其他不需要的字符散布。为确保完整打印阵列,请使用Console.WriteLine写入一个字符串。使用.NET 4.0之前可用的非通用Join,大多数对象数组都可以水平打印(取决于类型的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>()));

1
这与眼前的问题无关。OP甚至从未提到线程。
MechMK1

1
这个答案与手头的问题有关。它是使用LINQ和非通用string.Join方法的单线,.NET 3.5兼容解决方案,还可以防止其他线程的输出中断。如果您觉得我的措辞使答案在多线程问题上显得很沉重,那么与将唯一有效的解决方案声明为无关紧要并对其投下反对票相比,编辑将更有帮助。如果需要,请投反对票,但是当OP明确询问“ ...使用Console.WriteLine()吗?”时,是否使用Console.Write否决了答案?
G DeMasters

0

我已经写了一些扩展以适应几乎所有需求。
使用SeparatorString.FormatIFormatProvider可以扩展扩展名。

例:

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

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

一个解释将是有条理的。
彼得·莫滕森
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.