5.8. More on the Count Command

You have seen how you can count the number of characters in a string with a statement like

count theText

You can also use the count command to count the number of elements in a list. Combine this fact with the knowledge that enumerating a range of elements produces a list. You can now see how writing a statement like

count words in theText

can be used to count the number of words in a string.

As you see in the next Try It Out, the count command comes in handy when you want to count the number of items of a particular type in a string.

5.8.1.

5.8.1.1. Try It Out: Count the Number of Words in Some Text

In the following steps, you use the count command to count the number of elements of different types in a string.

  1. Type the following program into Script Editor:

    -- Using count
    
    set s to "The AppleScript Language rocks!"
    
    -- the length of s
    log (count s)
    
    -- the number of words in s
    log (count words in s)
    
    -- the number of characters in the first word
    log (count characters in the first word of s)
  2. Click the Event Log tab, run the program, and examine the log. You get the following results:

    (*31*)
        (*4*)
        (*3*)
5.8.1.2. How It Works

The output of this program is straightforward. First, the characters in s are counted. Next, the number of words in s are counted. Finally, the number of characters in the first word of s are counted.

5.8.2. Using length instead of count

Incidentally, before leaving this topic you should note that the length property can also ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.