Discuss Scratch
- Discussion Forums
- » Help with Scripts
- » Split a string at symbol
- awesomechapro
-
Scratcher
2 posts
Split a string at symbol
Hi all,
Recently I was bored and decided to for fun, make a calculator in scratch (I know it's pointless) However after a while of coding a ran into an issue. My calculator is storing the users inputs in one long string, eg. 942 + 647. During calculation though, I need to split that string at the + to get the 942 (first number) and the 647 (second number) separately. Essentially storing two separate values in one string. Is there an easy way to do this or do I just have to have multiple strings for the first number, the operation, and the second number.
Recently I was bored and decided to for fun, make a calculator in scratch (I know it's pointless) However after a while of coding a ran into an issue. My calculator is storing the users inputs in one long string, eg. 942 + 647. During calculation though, I need to split that string at the + to get the 942 (first number) and the 647 (second number) separately. Essentially storing two separate values in one string. Is there an easy way to do this or do I just have to have multiple strings for the first number, the operation, and the second number.
Last edited by awesomechapro (Dec. 17, 2022 06:56:30)
- AHypnoman
-
Scratcher
1000+ posts
Split a string at symbol
To make this simpler, you could store input in a list instead of a variable, but I'll answer as though that is not the case.
//I'll assume that user input is already stored in a variable called "input"If you want it to split on a set of character, not just one, create a list (For the following code I'll assume it's just called “split”) containing all the characters you want to split on and replace the if condition (the one that has the +) with this:
set [split index v] to [0]
delete all of [split output v]::list
repeat until <(letter (split index) of (input)) = []>
if <(letter (split index) of (input)) = [+]> then //replace the + with any symbol you want it to split on.
add [] to [split output v]
else
replace item (length of [split output v] :: list) of [list v] with (join(item (length of [split output v] :: list) of [split output v] :: list) (letter (split index) of (input)))
end
end
<[split v] contains (letter (split index) of (input)) ?>
Last edited by AHypnoman (Dec. 17, 2022 07:58:00)
- Discussion Forums
- » Help with Scripts
-
» Split a string at symbol
