How can I align text in columns using Console.WriteLine?

前端 未结 8 1233
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 22:11

I have a sort of column display, but the end two column\'s seem to not be aligning correctly. This is the code I have at the moment:

Console.WriteLine(\"Cust         


        
8条回答
  •  北海茫月
    2020-11-28 22:43

    I know, very old thread but the proposed solution was not fully automatic when there are longer strings around.

    I therefore created a small helper method which does it fully automatic. Just pass in a list of string array where each array represents a line and each element in the array, well an element of the line.

    The method can be used like this:

    var lines = new List();
    lines.Add(new[] { "What", "Before", "After"});
    lines.Add(new[] { "Name:", name1, name2});
    lines.Add(new[] { "City:", city1, city2});
    lines.Add(new[] { "Zip:", zip1, zip2});
    lines.Add(new[] { "Street:", street1, street2});
    var output = ConsoleUtility.PadElementsInLines(lines, 3);
    

    The helper method is as follows:

    public static class ConsoleUtility
    {
        /// 
        /// Converts a List of string arrays to a string where each element in each line is correctly padded.
        /// Make sure that each array contains the same amount of elements!
        /// - Example without:
        /// Title Name Street
        /// Mr. Roman Sesamstreet
        /// Mrs. Claudia Abbey Road
        /// - Example with:
        /// Title   Name      Street
        /// Mr.     Roman     Sesamstreet
        /// Mrs.    Claudia   Abbey Road
        /// List lines, where each line is an array of elements for that line.
        /// Additional padding between each element (default = 1)
        /// 
        public static string PadElementsInLines(List lines, int padding = 1)
        {
            // Calculate maximum numbers for each element accross all lines
            var numElements = lines[0].Length;
            var maxValues = new int[numElements];
            for (int i = 0; i < numElements; i++)
            {
                maxValues[i] = lines.Max(x => x[i].Length) + padding;
            }
            var sb = new StringBuilder();
            // Build the output
            bool isFirst = true;
            foreach (var line in lines)
            {
                if (!isFirst)
                {
                    sb.AppendLine();
                }
                isFirst = false;
                for (int i = 0; i < line.Length; i++)
                {
                    var value = line[i];
                    // Append the value with padding of the maximum length of any value for this element
                    sb.Append(value.PadRight(maxValues[i]));
                }
            }
            return sb.ToString();
        }
    }
    

    Hope this helps someone. The source is from a post in my blog here: http://dev.flauschig.ch/wordpress/?p=387

提交回复
热议问题