How would I turn a sentence entered by a user in AppleScript into separate variables for each word. For example, Lorem ipsum dolor sit amet
would be split by the space into different variables, Ex. var1 = lorem, var2 = ipsum
and so on. Below is what I've come up with so far, but I'm clearly getting nowhere.
set TestString to "1-2-3-5-8-13-21"
set myArray to my theSplit(TestString, "-")
on theSplit(theString, theDelimiter)
-- save delimiters to restore old settings
set oldDelimiters to AppleScript's text item delimiters
-- set delimiters to delimiter to be used
set AppleScript's text item delimiters to theDelimiter
-- create the array
set theArray to every text item of theString
-- restore the old setting
set AppleScript's text item delimiters to oldDelimiters
-- return the result
return theArray
end theSplit
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.
Split without $IFS variable In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.
Just use 'word' key word. Here is a small example of script :
set teststring to "1-2-3-5-8-13-21"
set Wordlist to words of teststring -- convert string to list of words
repeat with aword in Wordlist --loop through each word
log aword -- do what ever you need with aword
end repeat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With