Android Question How do I pad a string (left or right) to make a fixed length?

Todd Carlton

Member
Licensed User
Longtime User
How do I pad a string (left or right) to make a fixed length?

I used the String Function library for years and it was easy ...

MyReg = sf.Pad(RegNos,"0",6,False)

I'm moving away from sf and all I am looking for a really 'clean' solution.

Am I missing a really simple command for padding without using a library?

Thank you for any direction to fill this gap in my learning.
 
Last edited:

Sandman

Expert
Licensed User
Longtime User
I'm a fan of using hammers to whack problems with. Dead simple leaves dead problems, so to speak. So, for your exact scenario, many years ago I started doing it like this to pad to the right using a single character: Join to the right with max length of the character and then take the left part of desired length of the string.

So let's say we want a string that ten chars in total, and exclamation marks should be used as padding.

Start with this example string...

whiskey

...add ten exclamation marks so it's...

whiskey!!!!!!!!!!

...then cut out the ten leftmost characters:

whiskey!!!


No loop, just stupid simple logic. Cheers!
 
Upvote 0

Todd Carlton

Member
Licensed User
Longtime User
Thank you for the direction.

I have code where I include padded strings multiple times per line and was trying to avoid setting temporary variables (the string presented and variable retained are not always the padded string stored) but it looks like I am going to take your advice for expediency and move on.

Collection.Add(CollectionNumber & DateTime.Date(DateTime.now) & sf.Pad(Fields(23),"0",6,False) & "A000000.00||")

I appreciate your time to have answered.
 
Upvote 0

Sandman

Expert
Licensed User
Longtime User
I didn't really mention it, but just to make things (overly?) clear: You might want to consider adding a function to a code module, so you don't have snippets of this all over your code. If you do that, you would easily be able to create your own rightPad(myString, "0", 6), or something like that.
 
Upvote 0

Todd Carlton

Member
Licensed User
Longtime User
I'm going to give this a try...

Old:
Collection.Add(CollectionNumber & DateTime.Date(DateTime.now) & sf.Pad(Fields(23),"0",6,False) & "A000000.00||")
New (Solution):
Collection.Add(CollectionNumber & DateTime.Date(DateTime.now) & "000000".SubString2(0,6-Fields(23).Length) & Fields(23) & "A000000.00||")

Most of my pads are 15 or fewer characters. I just didn't want to start making up solutions if there was already something in place, which it seems like there might not be. sf.pad appears 84 times in my code so it was important to figure this out before I got too deep into conversion. ;)
 
Last edited:
Upvote 0

JohnC

Expert
Licensed User
Longtime User
This gives the option of specifying the pad character.

B4X:
Sub Pad(ItemToPad As String, ResultSize As Long, LeadPadding As String) As String
    'adds lead PADDING if ItemToPad is smaller then ResultSize
    Return Right(GenString(ResultSize, LeadPadding) & ItemToPad.Trim, ResultSize )
End Sub

Sub GenString(NumChar As Long, Character As String) As String
    Dim Z As Long
    Dim R As String
 
    For Z = 1 To NumChar
        R = R & Character
    Next

    Return R
End Sub

Sub Right(Text As String, Length As Long) As String
    Dim R As String

    Try
        If Length > Text.Length Then Length = Text.Length
        R = Text.SubString(Text.Length - Length)
    Catch
        R = ""
    End Try
    Return R
End Sub
 
Last edited:
Upvote 0

martha

Member
B4X:
'Pad a text with a selected character
'psText: Original text
'psCharacter: Padding character. If passed an empty string, a blank space will be used
'pnNewLength: Length of resulting text
'<code>
'PadText("Test", "-", 10, True)   'Result: "------Test"
'PadText("Test", "-", 10, False)  'Result: "Test------"
'</code>
Sub PadText(psText As String, psCharacter As String, pnNewLength As Int, pbLeading As Boolean) As String
    Dim cCharacter As Char = " "
    Dim sb As StringBuilder

    Try
        If psCharacter <> "" Then
            cCharacter = psCharacter.CharAt(0)
        End If
    Catch
        cCharacter = " "  ' default character: space
    End Try
    sb.Initialize
    If pbLeading Then
        For nI = 1 To pnNewLength - psText.Length
            sb.Append(cCharacter)
        Next
        sb.Append(psText)
    Else
        sb.Append(psText)
        For nI = 1 To pnNewLength - psText.Length
            sb.Append(cCharacter)
        Next
    End If
    Return sb.ToString
End Sub PadText
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
Here is my version, to pad right or left of the string:
Example:
B4X:
 Log(Pad("Tod", 9, "x", True))   'Todxxxxxx
B4X:
Sub Pad(Value As String, MaxLen As Int, PadChar As String, right As Boolean) As String
    Dim  MyLength As Int = Value.Length
    If MyLength >= MaxLen Then 
        Log("Cannot pad")
        Return Value
    End If
    For i = 1 To (MaxLen - MyLength) 
        If right Then
            Value =  $"${Value}${PadChar}"$
        Else
            Value = $"${PadChar}${Value}"$
        End If
    Next
    Return Value
End Sub
 
Upvote 0
Top