awyr_agored
awyr_agored

Reputation: 613

Rebol: how to split a string into characters

Using Rebol how do I split this string into characters (without using a c-like approach with loops)? I'm using version 2.7.8.2.5 which does not have the split method.

str: "Today is Monday"

I want to split the above into:

[ 'T' 'o' 'd' 'a' 'y' ' ' 'i' 's' ' ' 'M' 'o' 'n' 'd' 'a' 'y']

Parse method seems to only split a sentence into constituent words.

Thank you.

Upvotes: 2

Views: 254

Answers (3)

sqlab
sqlab

Reputation: 6436

Depending if you want to get single characters or strings with the length one you can use parse too with the following rules

>> str: "Today is Monday"
== "Today is Monday"
>> collect [parse/all str [some [copy x  skip (keep x)    ]     ]]
== ["T" "o" "d" "a" "y" " " "i" "s" " " "M" "o" "n" "d" "a" "y"] 
>> collect [parse/all str [some [x: skip (keep x/1)]]]
== [#"T" #"o" #"d" #"a" #"y" #" " #"i" #"s" #" " #"M" #"o" #"n" #"d" #"a" #"y"]

Red allows a tighter version

>>   parse str [collect [some [keep skip]]]
== [#"T" #"o" #"d" #"a" #"y" #" " #"i" #"s" #" " #"M" #"o" #"n" #"d" #"a" #"y"]

Upvotes: 0

In some Rebols (not Rebol2) you could use MAP-EACH to do this, e.g. map-each ch str [ch].

In Rebol2, COLLECT and KEEP are fairly general and powerful ways of building up blocks:

>> collect [foreach c str [keep c]]
== [#"T" #"o" #"d" #"a" #"y" #" " #"i" #"s" #" " #"M" #"o" #"n" #"d" #"a" #"y"]

I'll give you that one and let others list out the infinity of faster ways. :-)

Upvotes: 3

9214
9214

Reputation: 2193

If you don't want to use loops, there's one nifty trick:

>> head extract/into str 1 []  
== [#"T" #"o" #"d" #"a" #"y" #" " #"i" #"s" #" " #"M" #"o" #"n" #"d" #"a" #"y"]

OTOH, string! is already a series of char! values, so breaking it up into characters like that doesn't provide any clear benefit.

Upvotes: 4

Related Questions