Padding spaces to string

  • Thread starter Thread starter John
  • Start date Start date
J

John

Hi

How can I pad spaces to the right of a string so it always ends up with a
fixed given length?

Thanks

Regards
 
Hi

How can I pad spaces to the right of a string so it always ends up with a
fixed given length?

Thanks

Regards

Others mentioned PadRight - but... You can actually accomplish this with
string.format (or any other method, such as Console.WriteLine) that takes a
format specifier, if all you need is white space :). For instance:

' Pad to the right - string is left aligned
Dim s1 As String = String.Format("{0,-25}", "Hello, World!")

' pad to the left - string is right aligned
Dim s2 As String = String.Format("{0,25}", "Hello, World!")

Or...

' left aligned
Console.WriteLine ("{0,-25}", "Hello, World!")

' right aligned
Console.WriteLine ("{0,25}", "Hello, World!")

Just thought, I'd throw that out as an alternative :)
 
John said:
Hi

How can I pad spaces to the right of a string so it always ends up with a
fixed given length?

Thanks

Regards

I would go a little further than the other replies...

If the requirements are, you need to pass a fixed-length string (the string
cannot be more or less than 'n' characters):

Private Function MakeFixedLength( _
ByVal s As String, _
ByVal fixedLength As Integer _
) As String
If Not String.IsNullOrEmpty(s)
If s.Length > fixedLength
Return s.Remove(fixedLength)
ElseIf s.Length < fixedLength
Return s.PadRight(fixedLength)
End If
Return s
End If
Return New String(" "c, fixedLength)
End Function

Note: This will truncate the original string if the string was longer than
the specified fixedLength, create a new string if the original was null or
empty, append additional spaces to the right of the original string to make
it fixedLength, or return the original string if the string was already the
required length.

HTH,
Mythran
 
Back
Top