Padding spaces to string

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
 
A

Armin Zingler

John said:
Hi

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

The string has a PadRight method.


Armin
 
T

Tom Shelton

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 :)
 
M

Mythran

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top