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) \)))
  重複 ((字串長度\( (original) \)) - (character)) 次 
    變數 [letter v] 改變 (1)
    變數 [split 2 v] 設為 (字串組合 (split 2) 和 (字串中第 (character) 字\( (original) \)))

  變數 [split 1 v] 設為 [error]
  變數 [split 2 v] 設為 [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.

定義 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
  變數 [i v] 改變 (1)
新增項目 (Cstring) \( [split v] \)
Cookies help us deliver our services. By using our services, you agree to our use of cookies.