(Redirected from Separating a String into Words)

Often, it becomes the case that it is necessary to separate a string into some number of pieces. Custom blocks allow for a flexible method to accomplish this. There are two major types of string splitting: splitting into two at a point, and splitting into a list at a certain character (often used with spaces, to split into words).

Splitting Into Two

For this script, three variables need to be defined:

  • (letter) — a variable used for iterating through the string
  • (split 1) — the variable containing the first part of the string
  • (split 2) — the variable containing the second part of the string

The following script splits a string into two. For example, if the string is split after letter 3, letters 1-3 will be a separate string from letters 4+. For this tutorial, assume the following:

//character is a number input
define split string [original] after character (character)
set [letter v] to (0) //begins at the beginning
set [split 1 v] to [] //set it to nothing
set [split 2 v] to []
if <(character) < ((length of (original)) + (1))> then
 repeat (character)
  change [letter v] by (1)
  set [split 1 v] to (join (split 1) (letter (character) of (original)))
 end
 repeat ((length of (original)) - (character))
  change [letter v] by (1)
  set [split 2 v] to (join (split 2) (letter (character) of (original)))
 end
else
 set [split 1 v] to [error]
 set [split 2 v] to [error]

Splitting Into List

For this script, two variables and a list need to be defined:

  • (curr) - used to hold the current part to be added to the list
  • (i) - used while iterating over the string
  • (split::list) - the end result
define split [string] on [character]
set [curr v] to []
delete (all v) of [split v]
set [i v] to (1)
repeat (length of (string))
 if <(letter (i) of (string))=(character)> then
  add (curr) to [split v]
  set [curr v] to []
 else
  set [curr v] to (join(curr)(letter (i) of (string)))
 end
 change [i v] by (1)
end