Imports System
' Key Concepts
' Left-align text: "{0,-20}"
' Right-align text: "{0,10}"
' Negative width = left alignment
' Positive width = right alignment
Module Program
Sub Main()
Console.WriteLine("Fixed-Width Field Formatting Demo")
Console.WriteLine(New String("="c, 55))
' Print header row
Console.WriteLine(
FormatFixedWidth("Name", 20, FieldAlignment.Left) &
FormatFixedWidth("Age", 8, FieldAlignment.Right) &
FormatFixedWidth("Salary", 15, FieldAlignment.Right))
Console.WriteLine(New String("-"c, 43))
' Sample data
Console.WriteLine(
FormatFixedWidth("John Smith", 20, FieldAlignment.Left) &
FormatFixedWidth(35, 8, FieldAlignment.Right) &
FormatFixedWidth(72500.75D.ToString("C2"), 15, FieldAlignment.Right))
Console.WriteLine(
FormatFixedWidth("Mary Johnson", 20, FieldAlignment.Left) &
FormatFixedWidth(42, 8, FieldAlignment.Right) &
FormatFixedWidth(98500D.ToString("C2"), 15, FieldAlignment.Right))
Console.WriteLine(
FormatFixedWidth("David Lee", 20, FieldAlignment.Left) &
FormatFixedWidth(29, 8, FieldAlignment.Right) &
FormatFixedWidth(121500D.ToString("C2"), 15, FieldAlignment.Right))
End Sub
''' <summary>
''' Specifies text alignment within a fixed-width field.
''' </summary>
Public Enum FieldAlignment
Left
Right
End Enum
''' <summary>
''' Formats a string into a fixed-width field.
''' If the value exceeds the field width, it is truncated.
''' </summary>
''' <param name="value">Value to format.</param>
''' <param name="width">Field width.</param>
''' <param name="alignment">Left or right alignment.</param>
''' <returns>Formatted fixed-width string.</returns>
Public Function FormatFixedWidth(
value As Object,
width As Integer,
alignment As FieldAlignment) As String
If width <= 0 Then
Throw New ArgumentOutOfRangeException(
NameOf(width),
"Width must be greater than zero.")
End If
Dim text As String = If(value?.ToString(), String.Empty)
' Prevent overflow into adjacent columns.
If text.Length > width Then
text = text.Substring(0, width)
End If
Select Case alignment
Case FieldAlignment.Left
Return text.PadRight(width)
Case FieldAlignment.Right
Return text.PadLeft(width)
Case Else
Throw New ArgumentException("Invalid alignment.")
End Select
End Function
End Module
' run:
'
' Fixed-Width Field Formatting Demo
' =======================================================
' Name Age Salary
' -------------------------------------------
' John Smith 35 $72,500.75
' Mary Johnson 42 $98,500.00
' David Lee 29 $121,500.00
'