[REBOL] Re: joining strings
From: gregg:pointillistic at: 27-Jul-2009 19:08
ŞMB> What is the best way to join a block into a string with a separator?
ŞMB> I prefer not to use loop if it is possible.
ŞMB> b: ["a" "b" "1" "2"]
ŞMB> t: concat b "-"
ŞMB> == "a-b-1-2"
You got a couple replies already, but I'll add mine. In the past, some
of us have suggested that REJOIN would benefit from a /WITH
refinement, allowing you to specify an optional delimiting value.
Since REJOIN is a mezzanine, you could do that yourself.
I did that myself, but now I almost always use the following DELIMIT
function, combined with a REJOIN in front of it if need be. I've found
it to be more useful, with the skip refinement and ability to handle
I also use simple wrappers to make the intent clear, handle copying,
make-csv: func [block [block!]] [rejoin delimit copy block #","]
delimit: func [
"Insert a delimiter between series values."
series [series!] "Series to delimit. Will be modified."
value "The delimiter to insert between items."
/skip ;<-- be sure to use system/words/skip in this func
size [integer!] "The number of items between delimiters. Default is 1."
; By default, delimiters go between each item.
; MAX catches zero and negative sizes.
size: max 1 any [size 1]
; If we aren't going to insert any delimiters, just return the series.
; This check means FORSKIP should always give us a series result,
; rather than NONE, so we can safely inline HEAD with it.
if size + 1 > length? series [return series]
; We don't want a delimiter at the beginning.
series: system/words/skip series size
; Use size+n because we're inserting a delimiter on each pass,
; and need to skip over that as well. If we're inserting a
; series into a string, we have to skip the length of that
; series. i.e. the delimiter value is more than a single item
; we need to skip.
size: size + any [
all [list? series 0] ; lists behave differently; no need to skip dlm.
all [any-string? series series? value length? value]
all [any-string? series length? form value]
head forskip series size [insert/only series value]