Formatting a string: truncating or padding
I need to take a string of any length & make it exactly 5 characters long by either truncating it or padding it or neither.
So "abcdefgh" becomes "abcde", "abcde" stays "abcde" & "abc" becomes "abc " (2 spaces at the end).
I currently use this line of code:
Code:
Microsoft.VisualBasic.Left(myString, 5).PadRight(5, " "c)
it works, but it seems very hackish. Can anyone see a more elegant way? Thanks...
Re: Formatting a string: truncating or padding
I would use var.PadRight(5).Substring(0, 5) but other than that I can't see any issues?
Re: Formatting a string: truncating or padding
i can't improve it other than using uptodate .net methods:
vb Code:
MsgBox(myString.Substring(0, Math.Min(myString.Length, 5)).PadRight(5, " "c) & "|") 'added | for a visual cue
Re: Formatting a string: truncating or padding
Code:
Dim foo() As String = New String() {"abcdefgh", "edcba", "xyz"} 'strings to test
For Each s As String In foo
Dim sb As New System.Text.StringBuilder(s)
sb.Append(" ")
sb.Length = 5
Debug.WriteLine(sb.ToString)
'or
's = s.PadRight(5, " "c).Substring(0, 5)
s = s.PadRight(5, "*"c).Substring(0, 5) 'test
Debug.WriteLine(s)
Debug.WriteLine("")
Next