From Test-Scratch-Wiki

Revision as of 13:52, 1 April 2018 by Dnowba (talk | contribs) (Undo revision 17711 by Dnowba (talk))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Custom blocks allow for a flexible method to easily split a string into two pieces. For this tutorial, a custom block called "split string after (character)" will be used, in which the string splits after number parameter resembled by "character". 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:

  • "original"

— the variable resembling the original string

  • "split 1"

— the variable resembling the first half of the split string

  • "split 2"

— the variable resembling the second half of the split string

  • "letter"

— the variable used for iterating through the string

Scripting

The following script can split a string into two:

define split string after (character) //"character is a number input
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]

Another type of split is splitting a string on a certain character every time the character is in the string. So the string "I like cookies" split on the space, would be put in a list as "I" "like" "cookies". This type of splitting was used in this Pen Text Engine.[1] If you look inside, It splits the letter data on the comma and then uses the separate data. You can make this split like this.

Define Split [string] on [character]
set [Cstring v] to []
delete (all v) of [split v]//split is the list that the data will go in
set [i v] to (1)//i stands for iterator which is basically just counting things 
repeat (length of (string))
if <(letter (i) of (string))=(character)>
add (Cstring) to [split v]
set [Cstring v] to []
else
set [Cstring v] to (join(Cstring)(letter (i) of (string)// this won't work for any string greater than 10,240 characters because of the limit on the join block
end
change [i v] by (1)
end
add (Cstring) to [split v]
Cookies help us deliver our services. By using our services, you agree to our use of cookies.