У меня есть строковый массив, содержащий некоторые имена. Я хочу показать имена в моей консоли с выравниванием столбцов строки. Например, это мой массив:

{"First","Second","Third","Forth","Fifth","Sixth","Seventh","Eighth","Ninth"};

И затем отобразите их в этом формате:

First       Second      Third
Forth       Fifth       Sixth
Seventh     Eighth      Ninth

Как видите, эти имена выровнены в столбцах с пробелами между ними, это то, что я хочу. Как это сделать?

1
Al00X 26 Фев 2018 в 15:48

4 ответа

Лучший ответ
string[] str={"First","Second","Third","Forth","Fifth","Sixth","Seventh","Eighth","Ninth"};
    for (int i=0;i<str.Length-2;i+=3)
    Console.WriteLine ("{0,-10}   {1,-10}   {2,-10}",str[i],str[i+1],str[i+2]);

Демонстрационный код

https://repl.it/repls/CelebratedMuffledCybernetics

3
Jay Shankar Gupta 26 Фев 2018 в 12:55

Пример примера

     string[] val = { "First", "Second", "Third", "Forth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth" };
        for (int i = 0,j=1;  i < val.Length  ; i++) {

            Console.Write("{0}   ", val[i]);

            if (j % 3 == 0)
            {
                Console.WriteLine();
            }
            j++;
        }
        Console.ReadLine();
-1
ram 26 Фев 2018 в 13:08

Вы можете использовать добавление вкладок к вашей строке при печати их на экране с WriteLine, используя \t escape-последовательность.

Например, если вы печатаете 3 строки на экране, вы можете сделать это следующим образом:

Console.WriteLine("String 1" + "\t"
    + "String 2" + "\t" 
    + "String 3");
-2
DarthWader 26 Фев 2018 в 13:01

Поскольку вы выразили желание иметь полную адаптивность ширины столбцов, то ниже приводится полное решение. Как я уже сказал, это будет нелегко.

Это решение поддерживает слова любой длины (не длиннее ширины экрана). Результатом всегда является экран, заполненный настолько плотно, насколько это возможно, учитывая текст.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleDemo
{
    class Program
    {
        static IEnumerable<(string value, int row, int col)> Break(IEnumerable<string> data, int columnsNumber) =>
            data.Select((item, index) => (item, index / columnsNumber, index % columnsNumber));

        static IEnumerable<int> GetColumnWidths(IEnumerable<string> data, int columnsNumber) =>
            Break(data, columnsNumber)
                .GroupBy(tuple => tuple.col)
                .Select(group => group.Max(tuple => tuple.value.Length));

        static int RequiredScreenWidth(IEnumerable<string> data, int columnsNumber) =>
            GetColumnWidths(data, columnsNumber)
                .Sum() + columnsNumber - 1;

        static int SuggestNumberOfColumns(IEnumerable<string> data, int screenWidth) =>
            Enumerable.Range(1, int.MaxValue)
                .TakeWhile(columnsNumber => RequiredScreenWidth(data, columnsNumber) <= screenWidth)
                .DefaultIfEmpty(0)
                .Last();

        static IEnumerable<string> Pad(IEnumerable<string> data, int columnsNumber, int[] columnWidths) =>
            Break(data, columnsNumber)
                .Select(tuple => (tuple.value.PadRight(columnWidths[tuple.col], ' ')));

        static IEnumerable<string> GenerateRows(IEnumerable<string> paddedData, int columnsNumber) =>
            Break(paddedData, columnsNumber)
                .GroupBy(tuple => tuple.row)
                .Select(row => string.Join(" ", row.Select(tuple => tuple.value).ToArray()));

        static string GenerateColumnatedText(IEnumerable<string> paddedData, int columnsNumber) =>
            string.Join(Environment.NewLine, GenerateRows(paddedData, columnsNumber).ToArray());

        static void Main(string[] args)
        {
            IEnumerable<string> data = new[]
            {
                "Over", "time", "the", ".NET", "Framework", "has", "added", "many",
                "features", "that", "made", "concurrent", "programming", "a", "lot",
                "easier", "This", "started", "with", "the", "introduction", "of",
                "the", "thread", "pool", "got", "a", "lot", "more", "powerful", "with",
                "the", "task-based", "model", "and", "the", "Task", "Parallel",
                "Library", "and", "was", "improved", "even", "more", "by", "the",
                "addition", "of", "the", "async", "and", "await", "language",
                "keywords", "While", "creating", "and", "running", "concurrently",
                "is", "easier", "than", "ever", "one", "of", "the", "fundamental",
                "problems", "still", "exists", "mutable", "shared", "state", "Reading",
                "from", "multiple", "threads", "is", "typically", "very", "easy", "but",
                "once", "the", "state", "needs", "to", "be", "updated", "it", "gets",
                "a", "lot", "harder", "especially", "in", "designs", "that", "require",
                "locking", "An", "alternative", "to", "locking", "is", "making", "use",
                "of", "immutable", "state", "Immutable", "data", "structures", "are",
                "guaranteed", "to", "never", "change", "and", "can", "thus", "be",
                "passed", "freely", "between", "different", "threads", "without",
                "worrying", "about", "stepping", "on", "somebody", "else’s", "toes"
            };

            int columnsNumber = SuggestNumberOfColumns(data, 80);
            int[] columnWidths = GetColumnWidths(data, columnsNumber).ToArray();
            IEnumerable<string> padded = Pad(data, columnsNumber, columnWidths);
            string text = GenerateColumnatedText(padded, columnsNumber);

            Console.WriteLine(text);
            Console.ReadLine();
        }
    }
}

Применительно к тексту из демонстрации и к экрану шириной 60 символов, в результате получается идеально выровненный порядок столбцов:

Over         time        the         .NET         Framework
has          added       many        features     that
made         concurrent  programming a            lot
easier       This        started     with         the
introduction of          the         thread       pool
got          a           lot         more         powerful
with         the         task-based  model        and
the          Task        Parallel    Library      and
was          improved    even        more         by
the          addition    of          the          async
and          await       language    keywords     While
creating     and         running     concurrently is
easier       than        ever        one          of
the          fundamental problems    still        exists
mutable      shared      state       Reading      from
multiple     threads     is          typically    very
easy         but         once        the          state
needs        to          be          updated      it
gets         a           lot         harder       especially
in           designs     that        require      locking
An           alternative to          locking      is
making       use         of          immutable    state
Immutable    data        structures  are          guaranteed
to           never       change      and          can
thus         be          passed      freely       between
different    threads     without     worrying     about
stepping     on          somebody    else's       toes
0
Zoran Horvat 26 Фев 2018 в 13:26