How to count upper and lower case characters

This lesson will show how to count the number of upper case characters and lower case characters in a string.

An example stack

An example stack

All we need is a field to enter out 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 an lower case character add 1 to the lowe case count

Return the upper case and lower case count

That seems simple, now lets script in 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 lowecase 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

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


Add your comment

E-Mail me when someone replies to this comment