简体   繁体   English

每行打印出3个元素

[英]Printing out 3 elements in array per line

I have an array with x number of elements and want to print out three elements per line (with a for-loop). 我有一个包含x个元素的数组,并希望每行打印出三个元素(带有for循环)。

Example: 例:

123    343    3434
342    3455   13355
3444   534    2455

I guess i could use %, but I just can't figure out how to do it. 我想我可以使用%,但我无法弄清楚如何做到这一点。

For loop is more suitable: For循环更合适:

var array = Enumerable.Range(0, 11).ToArray();
for (int i = 0; i < array.Length; i++)
{
    Console.Write("{0,-5}", array[i]);
    if (i % 3 == 2)
        Console.WriteLine();
}

Outputs: 输出:

0    1    2
3    4    5
6    7    8
9    10   

Loop through the array 3 at a time and use String.Format() . 一次循环遍历数组3并使用String.Format()

This should do it... 这应该做到......

for (int i = 0; i < array.Length; i += 3)
    Console.WriteLine(String.Format("{0,6} {1,6} {2,6}", array[i], array[i + 1], array[i + 2]));

But if the number of items in the array is not divisable by 3, you'll have to add some logic to make sure you don't go out of bounds on the final loop. 但是如果数组中的项数不能被3除,那么你必须添加一些逻辑以确保你不会在最后一个循环中超出范围。

You perhaps need to fix the format spacing... 您可能需要修复格式间距...

for(int i=0;i<array.Length;i++)
{
    Console.Write(array[i] + " ");
    if((i+1)%3==0)
        Console.WriteLine(); 
}

Long... but with comments: 很长......但有评论:

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int count = list.Count;
int numGroups = list.Count / 3 + ((list.Count % 3 == 0) ? 0 : 1); // A partially-filled group is still a group!
for (int i = 0; i < numGroups; i++)
{
     int counterBase = i * 3;
     string s = list[counterBase].ToString(); // if this a partially filled group, the first element must be here...
     if (counterBase + 1 < count) // but the second...
          s += list[counterBase + 1].ToString(", 0");
     if (counterBase + 2 < count) // and third elements may not.
          s += list[counterBase + 2].ToString(", 0");
     Console.WriteLine(s);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM