Pad string

From Director Online Wiki
Jump to: navigation, search

This function pads a string with any given character to make it meet the required length. If input string is longer then specified the input string is cut short. Padding can be applied to the beginning or end of the file.

-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- inString : input string
-- padwith : character to pad with
-- totlen : total lenght
-- begEnd : true for applying the padding at the beginning of the files, false for at the end.
on padString  inString,padWith,totLen,begEnd
  if totLen < inString.length then
    return instring.char[1..(totLen-3)]&"..."
  else
    adder=totLen-inString.length
    repeat with cnt=1 to adder
      if inString.length+padWith.length<=totLen then
        if begEnd then
          put padWith before inString
        else
          put padWith after inString
        end if
      else
        exit repeat
      end if
    end repeat
    return inString
  end if
end

Here's an alternative version which does pretty much the same thing, but using recursion and without the right padding which I cannot think of a reason for needing.

on leftPad val, padNum, padChar
  if not stringP(val) or not integerP(padNum) then return void
  if not stringP(padChar) then padChar = "0"
  if val.length < padNum then return leftPad( padChar & val, padNum, padChar)
  return val
end