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. , .