KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility method to pad a string with another string
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: March 6, 2023

Below is a utility method to pad a string with another string to a desired length. The method can pad the string on either side.

/*
METHOD: padString
INPUT:
(1) original string to pad
(2) target length of output string
(3) string to use as padding (cannot be an empty string -> "")
(4) "left" = pad on the left side; "right" = pad on the right side
OUTPUT: original string padded with padding string (repeated if necessary) to the desired length
NOTE: If length of padding string is too long to stay within target length, it will be truncated from the end. If target length is less than or equal to length of string to pad, returns original string as is.
*/
If (Count parameters=4)
   If ($paddingStr#"")
     If (Length($src)>=$targetLength)
       $paddedStr:=$src
     Else
       $targetLength:=$targetLength-Length($src)

       If ($targetLength>Length($paddingStr))
         $repeatAmt:=Round($targetLength/Length($paddingStr); 0)+1
         $paddingStr:=$paddingStr*$repeatAmt
       End if

       If ($side="left")
         $paddedStr:=Substring($paddingStr; 1; $targetLength)+$src
       Else
         $paddedStr:=$src+Substring($paddingStr; 1; $targetLength)
       End if
     End if
   Else
     ALERT("Cannot use empty string to pad string.")
   End if
End if


Example 1 - mask the leading digits of a credit card number except the last 4:

$CCnum:="1234567890987654"
$lastFour:=Substring($CCnum; 13; 4)
$display:=padString($lastFour; 19; "**** "; "left") // **** **** **** 7654


Example 2 - format a receipt output:

$purchases:=New collection
$purchases.push(New object("item"; "masks"; "price"; "9.99"))
$purchases.push(New object("item"; "jeans"; "price"; "45.99"))
$purchases.push(New object("item"; "jacket"; "price"; "200.00"))
$purchases.push(New object("item"; "flowers"; "price"; "10.00"))

$receipt:=""

For each ($purchase; $purchases)
  $item:=$purchase.item
  $price:=$purchase.price
  $line:=padString($item; 20-Length($price); "."; "right")+$price+Char(Carriage return)
  $receipt:=$receipt+$line
End for each

receipt output:

masks...........9.99
jeans..........45.99
jacket........200.00
flowers........10.00