From: John on
Hi

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

Thanks

Regards


From: Armin Zingler on
John wrote:
> 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
From: Onur Güzel on
On Jan 8, 7:40 pm, "John" <i...(a)nospam.infovis.co.uk> wrote:
> Hi
>
> How can I pad spaces to the right of a string so it always ends up with a
> fixed given length?
>
> Thanks
>
> Regards

Look at ''String.PadRight''.

http://msdn.microsoft.com/en-us/library/system.string.padright.aspx

Note that, this method left-alings the string and is used to pad with
spaces on the right.

HTH,

Onur Güzel
From: Tom Shelton on
On 2009-01-08, John <info(a)nospam.infovis.co.uk> wrote:
> 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 :)

--
Tom Shelton
From: Mythran on


"John" <info(a)nospam.infovis.co.uk> wrote in message
news:eiOl#gbcJHA.3692(a)TK2MSFTNGP04.phx.gbl...
> 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