How can I format a string into a fixed width field in .Net?

0

Issue

I am trying to format a string of arbitrary length into a fixed width field for display.

Let’s use a width of 20 as an example, and call the string to be formatted s. I’m adding the formatted string to a StringBuilder named b.

Dim b As New System.Text.StringBuilder()
Dim s as New String

If the string I want to display is shorter than 20 characters, I can do this:

b.Append(s.PadRight(20))

or

b.AppendFormat("{0,-20}", s)

So far, so good. But, if the string is longer than 20 characters, I want the string to be truncated to 20 characters as it is appended. The code above appends the entire string.

I tried this:

b.Append(s.Substring(0,20).PadRight(20))

But, this fires an exception if the string was shorter than 20 characters.

So, I ended up with:

b.Append(s.PadRight(20).Substring(0,20))

This seems to do the job. The PadRight prevents the exception by making sure thet string has 20 characters before the Substring is performed.

I was wondering if there is an alternate method that would look more elegant and avoid padding the string just so prevent the substring from causing an exception. Have I missed a feature of String.Format that can accomplish this in one step?

Edited to add solution:

I ended up with the following code:

Module Extensions
    <Extension()> _
    Function AppendFixed(ByVal b As StringBuilder, ByVal s As String, ByVal width As Integer) As StringBuilder
        If s.Length >= width Then
            b.Append(s, 0, width)
        Else
            b.Append(s)
            b.Append(" ", width - s.Length)
        End If
        Return b
    End Function
End Module

This uses an extension method to clean up the syntax, as suggested by Joel and Merlyn, and uses the StringBulider Append overloads to avoid creating new strings that will have to be garbage collected, as suggested by supercat. Thanks to those that helped.

Solution

I was wondering if there is an alternate method that would look more elegant and avoid padding the string

(emphasis added)

<Extension()> _
Public Function AppendFixed(ByVal target As StringBuilder, ByVal value As String, ByVal desiredLength As Integer) As StringBuilder
    If value.Length < desiredLength Then value.PadRight(desiredLength)
    Return target.Append(value.Substring(0,desiredLength))
End Function

To use it:

b.AppendFixed(s, 20)

Answered By – Joel Coehoorn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More