Friday, February 29, 2008

If Statements and Strings

We are able to compare strings using If statements. This means that we can see if two strings are the same string [i.e. "george" = "george"], but more importantly we are able to compare the relationship between strings. That is, we can tell if a certain string comes before another string:

Dim strA, strB As String
strA = "cat"
strB = "dog"

If strA < strB Then
MsgBox(strA & " comes before " & strB, "")
ElseIf strA > strB Then
MsgBox(strA & " comes after " & strB, "")
Else
MsgBox(strA & " equals " & strB, "")
End If


Gives answer of "cat comes before dog"

One important thing to remember, however is that capital letters come before lowercase letters. This is because of the ASCII/ANSI coding of each letter in the computer.

The computer does not understand the word "cat" as we humans do. For the computer each letter has a binary value [binary = 1's and 0's]. Letters are given numbers in sequential order from 65-90 for A-Z and 97-122 for a-z. Since the capital letters have lower values, they are less than the lowercase letters and therefore "come first."


Dim strA, strB As String
strA = "cat"
strB = "Zebra"

If strA < strB Then
MsgBox(strA & " comes before " & strB, "")
ElseIf strA > strB Then
MsgBox(strA & " comes after " & strB, "")
Else
MsgBox(strA & " equals " & strB, "")
End If


Gives answer of "Zebra comes before cat"

If you want to eliminate case, you can use the .ToUpper and .ToLower functions.

No comments: