From Test-Scratch-Wiki
函式积木 allow for a flexible method to easily split a 字串 into two pieces. For this tutorial, a custom 积木 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
编写程式
The following script can split a string into two:
定義 split string after (character) //"character is a number input 變數 [letter v] 設為 (0) // begins at the beginning 變數 [split 1 v] 設為 [] // set it to nothing 變數 [split 2 v] 設為 [] 如果 <(character) ((字串長度\( (original) \)) + (1))> 那麼 重複 (character) 次 變數 [letter v] 改變 (1) 變數 [split 1 v] 設為 (字串組合 (split 1) 和 (字串中第 (character) 字\( (original) \))) end 重複 ((字串長度\( (original) \)) - (character)) 次 變數 [letter v] 改變 (1) 變數 [split 2 v] 設為 (字串組合 (split 2) 和 (字串中第 (character) 字\( (original) \))) end 變數 [split 1 v] 設為 [error] 變數 [split 2 v] 設為 [error] end
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.
定義 Split (string) on (character) 變數 [Cstring v] 設為 [] 刪除第 (全部 v) 項 \( [split v] \) // split is the list that the data will go in 變數 [i v] 設為 (1) // i stands for iterator which is basically just counting things 重複 (字串長度\( (string) \)) 次 如果 <(字串中第 (i) 字\( (string) \)) = (character)> 那麼 新增項目 (Cstring) \( [split v] \) 變數 [Cstring v] 設為 [] 變數 [Cstring v] 設為 (字串組合 (Cstring) 和 (字串中第 (i) 字\( (string) \)))// this won't work for any string greater than 10,240 characters because of the limit on the join block end 變數 [i v] 改變 (1) end 新增項目 (Cstring) \( [split v] \)