Useful padding function
Here is another function I use so often: pad: func [s [string!] n [integer!] /left /with c [char!]] [ head insert/dup either left [tail s] [s] either with [c] [#" "] n - length? s ] And here is the usage: >> pad "x" 5 == " x" >> pad/left "x" 5 == "x " >> pad/with "x" 5 #"*" == "****x" >> pad/with/left "x" 5 #"*" == "x****"
posted by: Endo 3-Aug-2010/11:07:33-7:00
I wonder if this is better? pad: func [s [string!] n [integer!] /left /with c [char!]] [ head insert/dup either left [tail] [head] s either with [c] [#" "] n - length? s ]
posted by: Graham 3-Aug-2010/22:56:19-7:00
It didn't work, it gives error without () and :, so I changed it to: pad2: func [s [string!] n [integer!] /left /with c [char!]] [ head insert/dup (either left [:tail] [:head] s) either with [c] [#" "] n - length? s ] Here is the benchmark (10.000.000 times) results: >> benchmark [pad2 "x" 5000] == 0:00:14.922 >> benchmark [pad2/left/with "x" 5000 #"*"] == 0:00:15.625 >> benchmark [pad "x" 5000] == 0:00:14.234 >> benchmark [pad/left/with "x" 5000 #"*"] == 0:00:16.453 It looks it's better if /left refinement used.
posted by: Endo 4-Aug-2010/3:02:24-7:00
Wait a minute, it still doesn't work: >> pad2/with/left "x" 10 #"*" == "*********x" >> pad2/with "x" 10 #"*" == "*********x" No error, but /left has no effect.
posted by: Endo 4-Aug-2010/3:12:30-7:00
Mine is a little different: pad: func ["Convert to string and pad to specified width." item width [integer!] /with padding [char!] /left /right /local num? ][ ; FIXME: left-zero-padding of negative numbers, right-zero-padding of integers num?: number? item unless with [padding: either num? [#"0"] [#" "]] item: form item head insert/dup either any [all [num? not right] left] [item] [tail item] padding width - length? item ] It defaults to left zero padding for numbers and right space padding for other values.
posted by: Kaj 3-Oct-2010/8:44:07-7:00
|