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 Variables
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:
define split string [string] 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 [] set [error v] to [false] if <(character) < ((length of (string)) + (1))> then repeat (character) change [letter v] by (1) set [split 1 v] to (join (split 1) (letter (letter) of (string))) end repeat ((length of (string)) - (character)) change [letter v] by (1) set [split 2 v] to (join (split 2) (letter (letter) of (string))) end else set [error v] to [true]
Splitting Into List
For this script, three variables and a list will be needed.
(letter)
- used to iterate through the string(split 1)
- used to store the first part of the string(split 2)
- used to store the second part of the string(split::list)
- the end result
define split string [string] 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 [] set [error v] to [false] delete all of [split v] if <(character) < ((length of (string)) + (1))> then repeat (character) change [letter v] by (1) set [split 1 v] to (join (split 1) (letter (letter) of (string))) end add (split 1) to [split v] repeat ((length of (string)) - (character)) change [letter v] by (1) set [split 2 v] to (join (split 2) (letter (letter) of (string))) end add (split 2) to [split v] else set [error v] to [true]