Comparing Strings

Because the ASCII value for uppercase characters is different than the ASCII value for lowercase characters the following condition

If "bob" = "Bob" Then

will be False.    "bob" is in fact greater than "Bob"

When comparing strings stored in variables you must be certain of the case of the characters. Since the values stored in string variables usually comes for a source outside of the program (user input, a file) you must be careful when comparing string variables to other strings to ensure that result of the comparison is not case sensitive (unless you intend it to be case sensitive).

We can use  the ToUpper or ToLower methods or UCase( ) or LCase( ) functions to eliminate potential problems with case.

Strings have built in methods ToUpper and ToLower that will return a string representing the original string in upper or lowercase respectively.

If the contents of a textbox named txtName contained the string "Green" the statement

 strName = txtName.Text.ToLower    'the Text property contains a string data type.

 

results in the string "green" being stored in the variable strName. The contents of the variable strName is  guaranteed to be in lower case and the following condition would not be case sensitive.

If strName < "h"

 

It would not be necessary to store the contents of the textbox in a variable. Instead  you could

If txtName.Text.ToUpper < "H" Then  

 

The same thing can be accomplished using a function

 

If UCase(txtName.Text) < "H" Then

 

 

NOTE:  Neither of the preceding two examples changes the value stored in txtName.Text. They both return a temporary string with the same letters in uppercase which is then compared to the string constant. The important thing is that the two operands in the condition are the same case when the condition is evaluated.