How do you pick out characters from a string? Basically I have a script which generates a string and i need to be able to pick out all the characters from 14 to 25. I also need to be able to pick out all the characters from 32 to 45 so i need a solution that can be changed to do any characters from X to Y. Can anyone help me?
set Stwing to "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
set FirstChar to 14 -- start character
set SecondChar to 17 -- end character
set thing to my GetCharStwing(Stwing, FirstChar, SecondChar) -- change values
log thing
on GetCharStwing(PassedStwing, Startchar, Endchar)
set ReturnString to ""
repeat until Startchar = Endchar + 1
set NowChar to character Startchar of PassedStwing
set ReturnString to (ReturnString & NowChar)
set Startchar to Startchar + 1
end repeat
return ReturnString
end GetCharStwing
set myString to "the best way to pick out characters from a string"
getChars(myString, 5, 12)
getChars(myString, 37, -1)
on getChars(myString, firstChar, lastChar)
-- this syntax if you want a list of each character
characters firstChar thru lastChar of myString
-- this syntax if you want the characters as a string
(characters firstChar thru lastChar of myString) as text
end getChars
You may find that this syntax is better for extracting a one string from another:
text firstChar thru lastChar of myString
It extracts the substring directly, instead of creating a list of characters first and then coercing that to text. It’s faster, uses less memory, and isn’t influenced by the current state of the text item delimiters.
set myString to "better way than the best way to pick out characters from a string"
getChars(myString, 17, 29)
getChars(myString, 37, -1)
on getChars(myString, firstChar, lastChar)
-- this syntax if you want a list of each character
characters firstChar thru lastChar of myString
-- this syntax if you want the characters as a string
text firstChar thru lastChar of myString
end getChars