KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: A utility for padding a string on the left or right side
PRODUCT: 4D | VERSION: 14.x | PLATFORM: Mac & Win
Published On: June 17, 2015

There are many situation were, for proper display, a string will need to be padded on the left or right side for proper visual display.

For example say the requirement is to create a column display but Tab characters are not supported. To create the column effect headers and variables will have to be padded on the left and right to create the format. In the image below the gray dots represent space characters. In this example the columns are five characters wide separated by three spaces. Numbers to be right justified, left padded, with text to be left justified, right padded.



Below is a utility that will properly pad a string on the left or right side with either a space, defalut, or with a provided character.

STR_Pad


If (True)
    If (False)
       Begin SQL
       /*
       Name: STR_Pad( $Txt_T; $Len_L {; $Padding_T {; $Left_B}})

       Purpose: Pad a string on left or right side

       $0 - TEXT - Padded string
       $1 - TEXT - Source string
       $2 - LONGINT - Desired length
       { $3 - TEXT - Leader character. Space by default. }
       { $4 - BOOLEAN - TRUE = Pad left side, FALSE = Pad right side }
       */
       End SQL
    End if
    C_TEXT($MethodName_T)
    $MethodName_T:=Current method name
    //===================== Declare Variables ==================================
    //method_parameters_declarations
    C_TEXT($0)
    C_TEXT($Txt_T;$1)
    C_LONGINT($Len_L;$2)
    C_TEXT($Padding_T;$3)
    C_BOOLEAN($Left_B;$4)
    //--------------------------------------------------------------------------
    //local_variable_declarations
    C_LONGINT($Ndx;$SOA;$RIS;$Params_L)

End if
//====================== Initialize and Setup ================================

$Params_L:=Count parameters
$Txt_T:=$1
$Len_L:=$2
$SOA:=Length($Txt_T)

If ($SOA<$Len_L) // Can't be padded
    $Left_B:=True
    $Padding_T:=" "

    If ($Params_L>2)
       $Padding_T:=$3
       If ($Params_L>3)
          $Left_B:=$4
       End if
    End if

    //======================== Method Actions ==================================

    If ($Left_B)
       $Txt_T:=($Padding_T*($Len_L-$SOA))+$Txt_T
    Else
       $Txt_T:=$Txt_T+($Padding_T*($Len_L-$SOA))
    End if

    //======================== Clean up and Exit =================================

End if

$0:=$Txt_T