revUp - Updates and news for the LiveCode community
Issue 137 | August 3rd 2012 Contact the Editor | How to Contribute

Counting Characters
This lesson shows how to count the number of upper case characters and lower case characters in a string

by Elanor Buchanan

Livecode is excellent at manipulating text, and this example demonstrates a nifty way to identify and count upper vs lower case characters.

An example stack

sample stack

All we need is a field to enter our string into and a button to call the handler which counts the number of upper and lower case characters.

What our handler needs to do

Now we need to decide what our function will do.

Check each character:
If it is an upper case character add 1 to the upper case count
If it is a lower case character add 1 to the lower case count
Return the upper case and lower case count

That seems simple, now lets script it in LiveCode

The caseSensitive property

In order to identify whether a character is upper or lower case we need to set the caseSensitive property to true, by default this property is set to false.

Using toLower and toUpper

Now that LiveCode is case sensitive when performing text comparisons how do we check whether a character is lower or upper case? We can do this using the toLower and toUpper functions. These functions convert strings to all lower or all upperc ase letters.

By converting a character to lower case and then comparing it to the original character we can identify whether it was originally lowercase or not.

For example

set the caseSensitive to true
put toLower("a") is "a"

returns true

put toUpper("a") is "a"

returns false

so we know the original character was lower case.

The mouseUp handler

LiveCode allows you to step through each character in a string using the repeat for each control structure. This makes the process of checking each character (or word, or line, or item) very simple and straightforward.

on mouseUp
    local tString
    put field "entry" into tString
    set the caseSensitive to true
    repeat for each char tChar in tString
        if toLower(tChar) is tChar then
            ## If we make the character lower case is it the same as the original character?
            add 1 to tLowercaseCount
        end if

        if toUpper(tChar) is tChar then
            ## If we make the character upper case is it the same as the original character?
            add 1 to tUppercaseCount
        end if
    end repeat
    answer "Lower case characters:" & tLowercaseCount && "Upper case characters:" & tUppercaseCount
end mouseUp

That's it! I hope you find this a useful technique.

Hanson Schmidt-Cornelius

About the Author

Elanor Buchanan is a Senior Software Developer for RunRev Ltd.

 

Main Menu

What's New

Get Your RunRevLive.13 Ticket Today