From Test-Scratch-Wiki
With Scratch's limited string manipulation capabilities, moving part of a string to a different position within that same string requires a workaround. A custom block set to "run without screen refresh" can be used to rapidly move a substring to another location in its base string.
Programming
The following custom block will move the specified sub of a base string to a different position (index) within the body (base) string.
define move character (start) through (last) of (base) to position (pos) set [i v] to (start) set [group1 v] to [] repeat (((last) - (start)) + (1)) set [group1 v] to (join (group1) (letter (i) of (base))) change [i v] by (1) end set [group2 v] to [] set [i v] to [1] repeat ((start) - (1)) set [group2 v] to (join (group2) (letter (i) of (base))) change [i v] by (1) end set [i v] to ((last) + (1)) repeat ((length of (base)) - (last)) set [group2 v] to (join (group2) (letter (i) of (base))) change [i v] by (1) end set [compiled v] to [] //will result in the finished string set [i v] to [1] repeat ((pos) - (1)) set [compiled v] to (join (compiled) (letter (i) of (group2))) change [i v] by (1) end set [compiled v] to (join (compiled) (group1)) //inserts the moved substring to the proper position set [i v] to (pos) repeat (((length of (base)) - (pos)) + (1)) set [compiled v] to (join (compiled) (letter (i) of (group2)))
Explanation
The very first section of the base string that must be grouped unto an independent variable, called group1
, is the substring of the body string that is to be removed. Afterwards, the substring is actually removed from the string, and the remaining characters are grouped into a variable called group2
. To finish the movement, the variable "compiled" results with the finished strings joined together in the proper sequential order.