Re: Newbie. How do I count "i"?
Re: Newbie. How do I count "i"?
- Subject: Re: Newbie. How do I count "i"?
- From: Mr Tea <email@hidden>
- Date: Sat, 26 Jan 2002 12:54:58 +0000
This from Steen at @491 on Sat, Jan 26, 2002
>
set z to "ideas how to do this?"
>
count every character = "i" in z
>
>
When I do this I get an error.
Hi, Steen.
You need to break down the string represented by your variable 'z' into a
list of individual characters, then loop through them...
~~~~~~~~~~~~~~~~
set z to every character of "Itsy bitsy teeny weeny yellow polka dot bikini"
set theTotal to 0
repeat with theChar in z
if theChar as string is "i" then set theTotal to theTotal + 1
end repeat
theTotal -->5
~~~~~~~~~~~~~~~~
If you only want to count lower case (or upper case) instances of a
letter, wrap the repeat loop in a 'considering case' block, like this...
~~~~~~~~~~~~~~~~
set z to every character of "Itsy bitsy teeny weeny yellow polka dot bikini"
set theTotal to 0
considering case
repeat with theChar in z
if theChar as string is "i" then set theTotal to theTotal + 1
end repeat
end considering
theTotal -->4
~~~~~~~~~~~~~~~~
Or you could take a totally different approach, using AppleScript's text
item delimiters...
~~~~~~~~~~~~~~~~
set z to "Itsy bitsy teeny weeny yellow polka dot bikini"
copy AppleScript's text item delimiters to ATIDs
set AppleScript's text item delimiters to "i"
copy (count of text items of z) to theTotal
set AppleScript's text item delimiters to ATIDs
theTotal - 1 -->4
~~~~~~~~~~~~~~~~
Here, the number of 'text items' returned is 1 greater than the number of
delimiters. Note that this method always considers case (is this
inconsistency on the part of AppleScript?) so you'd have to run it
through twice to count upper and lower case letters. Note also that it's
considered safe practice to restore Applescript's text item delimiters to
their original setting after changing them.
And finally, be aware that these suggestions the handiwork of an
AppleScript hobbyist. Pro scripters on this list may have more efficient
solutions to offer.
Mr Tea
--
"Always remember to warm the pot."