How to format a string using fixed-width fields in C#

4 Answers

0 votes
using System;

class Program
{
    static void Main()
    {
        String str = "CSharp";

        Console.Write("{0, 3},{1, 10},{2, 4}", str, "abcd", "123");
    }
}


/*
run:

CSharp,      abcd, 123

*/

 



answered Apr 12, 2025 by avibootz
0 votes
using System;

class Program
{
    static void Main()
    {
        String fileName = "abc.cs";
        
        String str = String.Format("{0, 3} {1, 8}", fileName, "17MB");

        Console.Write(str);
    }
}


/*
run:

abc.cs     17MB

*/

 



answered Apr 12, 2025 by avibootz
0 votes
using System;

// {value,-20}  // Left-align in 20-character field
// {value,20}   // Right-align in 20-character field

public class Program {
    public static void Main(string[] args) {
        string name = "John Smith";
        int age = 47;
        decimal salary = 152500.75m;

        Console.WriteLine($"{name,-20}{age,8}{salary,15:C2}");
    }
}


/*
run:

John Smith                47    $152,500.75

*/

 



answered Oct 17 by avibootz
0 votes
using System;

namespace FixedWidthFieldsExample
{
    /// <summary>
    /// Specifies field alignment.
    /// </summary>
    public enum FieldAlignment
    {
        Left,
        Right
    }

    /// <summary>
    /// Utility class for fixed-width formatting.
    /// </summary>
    public static class FixedWidthFormatter
    {
        /// <summary>
        /// Formats a value into a fixed-width field.
        /// Values longer than the specified width are truncated.
        /// </summary>
        /// <param name="value">Value to format.</param>
        /// <param name="width">Field width.</param>
        /// <param name="alignment">Field alignment.</param>
        /// <returns>Formatted string.</returns>
        public static string FormatField(object value, int width, FieldAlignment alignment)
        {
            if (width <= 0) {
                throw new ArgumentOutOfRangeException(
                    "width",
                    "Width must be greater than zero.");
            }

            string text = value == null
                ? String.Empty
                : value.ToString();

            // Truncate text that exceeds the field width.
            if (text.Length > width) {
                text = text.Substring(0, width);
            }

            if (alignment == FieldAlignment.Left) {
                return text.PadRight(width);
            }

            return text.PadLeft(width);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Employee Report");
            Console.WriteLine(new string('=', 50));

            // Print column headers.
            PrintHeader();

            // Print data rows.
            PrintEmployee("John Smith", 35, 72500.75m);
            PrintEmployee("Mary Johnson", 42, 98500.00m);
            PrintEmployee("David Lee", 29, 131500.00m);

            Console.WriteLine();
            Console.WriteLine("Additional Examples");
            Console.WriteLine(new string('-', 50));

            // Left-aligned text.
            Console.WriteLine(
                FixedWidthFormatter.FormatField(
                    "Product A", 20, FieldAlignment.Left)
                +
                FixedWidthFormatter.FormatField(
                    "In Stock", 15, FieldAlignment.Left));

            // Right-aligned numeric value.
            Console.WriteLine(
                FixedWidthFormatter.FormatField(
                    "Total", 20, FieldAlignment.Left)
                +
                FixedWidthFormatter.FormatField(
                    "12345.67", 15, FieldAlignment.Right));

            // Example showing truncation.
            Console.WriteLine(
                FixedWidthFormatter.FormatField(
                    "This string is longer than twenty characters",
                    20,
                    FieldAlignment.Left));
        }

        /// <summary>
        /// Prints the table header.
        /// </summary>
        static void PrintHeader()
        {
            Console.WriteLine(
                FixedWidthFormatter.FormatField(
                    "Name", 20, FieldAlignment.Left)
                +
                FixedWidthFormatter.FormatField(
                    "Age", 8, FieldAlignment.Right)
                +
                FixedWidthFormatter.FormatField(
                    "Salary", 15, FieldAlignment.Right));

            Console.WriteLine(new string('-', 43));
        }

        /// <summary>
        /// Prints a formatted employee record.
        /// </summary>
        static void PrintEmployee(string name, int age, decimal salary)
        {
            Console.WriteLine(
                FixedWidthFormatter.FormatField(
                    name, 20, FieldAlignment.Left)
                +
                FixedWidthFormatter.FormatField(
                    age, 8, FieldAlignment.Right)
                +
                FixedWidthFormatter.FormatField(
                    salary.ToString("C2"),
                    15,
                    FieldAlignment.Right));
        }
    }
}



/*
run:

Employee Report
==================================================
Name                     Age         Salary
-------------------------------------------
John Smith                35     $72,500.75
Mary Johnson              42     $98,500.00
David Lee                 29    $131,500.00

Additional Examples
--------------------------------------------------
Product A           In Stock       
Total                      12345.67
This string is longe

*/

 



answered Oct 17 by avibootz
...