Changing the lines of a string using a repeat loop
Posted: Sat Oct 10, 2020 11:03 am
What's the best way to iterate over the lines of a string, editing those lines, and having the original string reflect those edits?
Examples will use this string, "s":
30 50 20
40 60 90
45 25 80
i.e.: put "30 50 20" &return& "40 60 90" &return& "45 25 80" into s
"repeat for each" doesn't change the original container
"repeat with" changes the original container, but we don't get to use the nice "repeat for each" syntax, and our code gets verbose
Combination of the above two methods
Build a new string based on the changes
There are probably other ways.
How do you all handle this?
Examples will use this string, "s":
30 50 20
40 60 90
45 25 80
i.e.: put "30 50 20" &return& "40 60 90" &return& "45 25 80" into s
"repeat for each" doesn't change the original container
Code: Select all
repeat for each line theLine in s
put word 1 of theLine -1 into word 1 of theLine
put word 2 of theLine +2 into word 2 of theLine
put word 3 of theLine *3 into word 3 of theLine
end repeat
answer s // Returns the original string, 30 50 20...
"repeat with" changes the original container, but we don't get to use the nice "repeat for each" syntax, and our code gets verbose
Code: Select all
repeat with i = 1 to the number of lines of s
put (word 1 of line i of s) -1 into word 1 of line i of s // parentheses are unnecessary, just for readability
put (word 2 of line i of s) +2 into word 2 of line i of s
put (word 3 of line i of s) *3 into word 3 of line i of s
end repeat
answer s // Returns 29, 52, 60...
Combination of the above two methods
Code: Select all
put 1 into i
repeat for each line theLine in s
put (word 1 of theLine) -1 into word 1 of line i of s // parentheses are unnecessary, just for readability
put (word 2 of theLine) +2 into word 2 of line i of s
put (word 3 of theLine) *3 into word 3 of line i of s
add 1 to i
end repeat
answer s // Returns 29, 52, 60...
Build a new string based on the changes
Code: Select all
repeat for each line theLine in s
put word 1 of theLine -1 into word 1 of theLine
put word 2 of theLine +2 into word 2 of theLine
put word 3 of theLine *3 into word 3 of theLine
put theLine & return after newString
end repeat
answer newString // Returns 29, 52, 60...
There are probably other ways.
How do you all handle this?