Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

[REBOL] Re: Constant size string variable?

From: greggirwin:mindspring at: 1-Dec-2001 15:56

Hi Bob, << I need a string variable that is always ten characters long. ...If less than ten are entered those character positions are filled with a plus sign (+) preceding the numbers. >> I don't know if this is the best way, but it should work. Watch for line wrap! mk-string: func [n[integer!] ch[string!]][to-string array/initial n ch] justify: func [ {Justify the given string to the specified width. Uses: mk-string left} s[string!] "The string to justify" wd[integer!] "The target width, in characters" /left "Left justify the string (default)" /center {Center justify the string. If the total length of the padding is an odd number of characters, the extra character will be on the right.} /right "Right justify the string" /with {Allows you to specify filler other than space. If you specify a string more than 1 character in length, it will be repeated as many times as necessary.} filler[string! char!] "The character, or string, to use as filler" /local pad-len pad-str half-pad ][ if (length? s) >= wd [return s] if not with [filler: " "] pad-len: wd - length? s pad-str: copy/part (mk-string pad-len filler) pad-len either center [ ; rejoin [pad s pad (extra-char?)] half-pad: copy/part pad-str to-integer (pad-len / 2) rejoin [ half-pad s half-pad ; This is getting longer and uglier by the minute. It may be an odd ; number of fill chars, and they may give us a single char. ;either pad-len // 2 = 0 [""][pick filler (length? half-pad) + 1] either (pad-len // 2 = 0) [ "" ][ either ((length? filler) > 1) [ pick filler (length? half-pad) + 1 ][ filler ] ] ] ][ rejoin either right [[pad-str s]][[s pad-str]] ] ]
>> justify/right/with "" 10 "+"
== "++++++++++"
>> justify/right/with "1" 10 "+"
== "+++++++++1"
>> justify/right/with "4321" 10 "+"
== "++++++4321"
>> justify/right/with "987654321" 10 "+"
== "+987654321" HTH! --Gregg