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 our string into and a button to call the handler which counts the number of upper and lower case characters. Name the field "entry" and the button "Count".

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 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. We will set it to true in our script.

Using toLower and toUpper

Once 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 upper case 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

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. Enter this script into the code editor for the "Count" button:

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

Switch to Run mode and test it. Enter some characters in the field to test for upper or lower case.

0 Comments

Add your comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.