• No results found

There are several ways to compare String objects in VB.NET. The most obvious way is to use the relational operators, which for most situations will work just fine. However, there are situations where other comparison techniques prove to be more useful, such as if we want to know whether a string is greater than, less than, or equal to another string. For these type of situations we have to use methods found in the String class.

Strings are compared with each other much as we compare numbers. How- ever, since it’s not obvious whether “a” is greater than or less than “H”, we have to have some sort of numeric scale to use. That scale is the Unicode table. Each character (actually every symbol) has a Unicode value, which the operating system uses to convert a character’s binary representation to that character. You can determine a character’s Unicode value by using the ASC function. ASC actually refers to the ASCII code of a number. ASCII is an older numeric code that precedes Unicode, and the ASC function was first developed before Unicode subsumed ASCII.

The ASC function takes a character as an argument and returns the numeric code for that character. For example, consider the following code:

Dim charCode As Integer charCode = ASC("a")

Here the value 97 is stored in the variable.

Two strings are compared, then, by actually comparing their numeric codes. The strings “a” and “b” are not equal because code 97 is not code 98. The CompareTo method actually lets us determine the exact relationship between two String objects. We’ll see how to use that method shortly.

The first comparison method we’ll examine is the Equals method. This method is called from a String object and takes another String object as its argument. It then compares the two String objects character by character. If they contain the same characters (based on their numeric codes), the method returns True. Otherwise, the method returns False. The method is called like this:

Working with the String Class 159

Dim s1 As New String("foobar") Dim s2 As String = "foobar" If (s1.Equals(s2)) Then

Console.WriteLine("They are the same.") Else

Console.WriteLine("They are not the same.") End If

The next method for comparing strings is CompareTo. This method also takes a string as an argument but it doesn’t return a Boolean value. Instead, the method returns 1,−1, or 0, depending on the relationship between the passed-in string and the string instance calling the method. Here are some examples:

Dim s1 As New String("foobar") Dim s2 As String = "foobar"

Console.WriteLine(s1.CompareTo(s2))' Returns 0 s2 = "foofoo"

Console.WriteLine(s1.CompareTo(s2))' Returns -1 s2 = "fooaar"

Console.Writeline(s1.CompareTo(s2))' Returns 1

If two strings are equal, the CompareTo method returns a 0; if the passed- in string is “below” the method-calling string, the method returns a −1; if the passed-in string is “above” the method-calling string, the method returns a 1.

An alternative to the CompareTo method is the Compare method, which is usually called as a class method. This method performs the same type of comparison as the CompareTo method and returns the same values for the same comparisons. The Compare method is used like this:

Dim s1 As New String("foobar") Dim s2 As String = "foobar"

Dim compVal As Integer = String.Compare(s1, s2) Select Case compVal

Case 0

Console.WriteLine(s1 & " " & s2 & " are equal") Case 1

Case 2

Console.WriteLine(s1 & " is greater than " & s2) Case Else

Console.WriteLine("Can't compare.") End Select

Two other comparison methods that can be useful when working with strings are StartsWith and EndsWith. These instance methods take a string as an argument and return True if the instance either starts with or ends with the string argument.

Next we present two short programs that demonstrate the use of these methods. First, we’ll demonstrate the EndsWith method:

Module Module1 Sub Main()

Dim nouns() As String = {"cat", "dogs", "bird", _ "eggs", "bones"}

Dim pluralNouns As New Collection Dim noun As String

For Each noun In nouns

If (noun.EndsWith("s")) Then pluralNouns.Add(noun) End If

Next

For Each noun In pluralNouns Console.WriteLine(noun) Next

Console.Read() End Sub

End Module

First, we create an array of nouns, some of which are in plural form. Then we loop through the elements of the array, checking to see whether any of the nouns are plurals. If a plural is found, it is added to a collection. Then we loop through the collection, displaying each plural.

Working with the String Class 161

We use the same basic idea in the next program to determine which words start with the prefix “tri”:

Module Module1 Sub Main()

Dim words() As String = {"triangle", "diagonal", _ "trimester", "bifocal", _ "triglycerides"}

Dim triWords As New Collection Dim word As String

For Each word In words

If (word.StartsWith("tri")) Then triWords.Add(word)

End If Next

For Each word In triWords Console.WriteLine(word) Next

Console.Read() End Sub

End Module

There is one additional comparison technique we need to examine that is not part of the String class: the Like operator. This operator works in much the same way as the regular expression engine (discussed in the next chapter), but without all the flexibility of regular expressions. However, the Like operator is able to discern many simple patterns that come up frequently in string- processing situations.

With this operator, a string is compared to a pattern. If there is a match, the expression returns True; otherwise the expression returns False. The pattern can consist of either a complete string or a string made up of characters and special symbols that are used as wildcards. These wildcards can be used to match any single character, number, or ranges of characters and/or numbers. The wildcards and range operators used in Like comparisons are the following:

?: matches any single character, *: matches zero or more characters,

#: matches any single digit,

[char-list]: matches any character in the list, and [!char-list]: matches any character not in the list. Here are some examples using the Like operator: Module Module1

Sub Main()

Dim s1 As String = "foobar" Dim aMatch As String

aMatch = IIf(s1 Like "foo?ar", "match", "no match") Console.WriteLine(aMatch)

aMatch = IIf(s1 Like "f*", "match", "no match") Console.WriteLine(aMatch)

Dim s2 As New String("H2")

aMatch = IIf(s2 Like "[hH][0-9]", "match", _ "no match")

Console.WriteLine(aMatch) Console.Read()

End Sub End Module

The output from this program is as follows: match

match match

The first match works because the “?” in the pattern “foo?ar” matches the “b” in “foobar”. The second match works because the first letter in the string matches the first letter in the pattern and the “*” in the pattern matches any of the other characters in the string. Be careful when using the asterisk in a pattern because it tends to match even when you don’t want it to, leading to it being called a “greedy” operator. (Such “greedy” behavior will be discussed in thenext chapter.)

The most interesting match in the program is the last one. This exam- ple might be useful when processing a bunch of HTML text in search of heading tags. A heading tag in HTML starts with the letter “H” (or “h”),

Working with the String Class 163

followed by a digit indicating the level of the heading. The pattern we used “[hH] [0-9]” leads the Like operator to look for either an “h” or an “H” in the first character and any digit 0 through 9 in the second character. Again, we’ll see more examples of this behavior in thenext chapter when we discuss regular expressions.