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

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

As an example, use a width of 20 and call the formatted string s. I am adding a formatted string to a StringBuilder named b.

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

If the line 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 added. The above code adds the whole line.

I tried this:

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

But this throws an exception if the string was less than 20 characters.

So, I did:

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

This seems to do the job. PadRight prevents an exception by making sure that thet string has 20 characters before executing a substring.

, , , , . String.Format, ?

:

:

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

, , StringBulider Append, , , supercat. , .

+5
4

, ,

( )

<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

:

b.AppendFixed(s, 20)
+6

, . :

Imports System.Runtime.CompilerServices

Module StringExtensions

    <Extension()> _
    Public Function AsFixedWidth(ByVal value As String, desiredLength As Integer) As String
        return value.PadRight(desiredLength).Substring(0,desiredLength)
    End Function

End Module

:

b.Append(s.AsFixedWidth(20))
+3

, , , StringBuilder. , , , , .

, , . , ('', requestLength-TheString.Length). , TheString.Substring(0, requestLength).

If you need to add something to StringBuilder, and the source string is no longer needed, add the string, and then use the (char, int) Append overload to add the add-on, if necessary. If the source string is too long, use (String, int, int) Append overloading to add only the correct part.

+1
source

Function MakeFixedLength (ByVal str As String, ByVal requiredLength As Integer, ByVal LR As String, ByVal chr As Char) As String

    If str.Length >= desiredLength Then

        Return str.Substring(0, desiredLength)

    Else

        If LR = "L" Then

            Return str.PadLeft(desiredLength, chr).Substring(0, desiredLength)

        Else

            Return str.PadRight(desiredLength, chr).Substring(0, desiredLength)

        End If

    End If

End Function
0
source

All Articles