Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

530 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

In this chapter, we’ll explore the members of the String and StringBuilder classes, which handle strings, and the members of the DateTime and TimeSpan classes, which handle dates and time. As I go along, I will mention the equivalent VB functions for the readers already familiar with VB6. If you’re porting old VB applications to VB.NET, the string and date functions of VB6 still work with VB.NET, but you should gradually replace them with the newer classes. If you’ve written applications that manipulate strings extensively, you should take the time to replace the older string functions with the equivalent methods of the StringBuilder class.

Handling Strings and Characters

The new Framework provides two classes for manipulating text: the String and the StringBuilder classes. The String object represents fixed-length strings, which you can’t edit. Once you assign a value to a String object, that’s it. You can examine the string, locate words in it, parse it, but you can’t edit it. The String class also exposes methods like the Replace and Remove methods, which replace a section of the string with another or remove a range of characters from the string. These methods, however, don’t act on the string directly: they replace or remove parts of the original string and then return the result as a new string.

The StringBuilder class is similar to the String class: it stores strings, but it can manipulate them in place. The distinction between the two classes is that the String class is for static strings, while the StringBuilder class is for dynamic strings. Use the String class for strings that don’t change frequently in the course of an application and the StringBuilder class for strings that grow and shrink frequently. The two classes expose similar methods, but the String class’s methods return new strings; if you need to manipulate large strings extensively, using the String class may fill the memory quite fast.

Any code that manipulates strings must also be able to manipulate individual characters. In previous versions of Visual Basic, characters were indistinguishable from strings; they were one-character strings. VB.NET introduces the Char class, which not only stores characters but also exposes numerous methods for handling characters. Both the String and StringBuilder classes provide methods for storing strings into arrays of characters, as well as converting character arrays into strings. After extracting the individual characters from a string, you can process them with the members of the Char class. We’ll start our discussion of text-handling features of VB.NET with an overview of the Char data type, and we’ll continue with the other two major components, the String and StringBuilder classes.

VB6 VB.NET

The Char class is new to VB.NET, and it exposes numerous methods for handling characters. You will find this data type especially useful in validating user-supplied strings, as you no longer need to write code to figure out whether a character is a digit or letter, a special character, and so on. There are now methods you can call to find out the type of character stored in a Char variable.

The StringBuilder is also new to VB.NET. The old string functions of Visual Basic are now implemented as methods of the String and StringBuilder classes.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING STRINGS AND CHARACTERS 531

The Char Class

The Char data type stores characters as individual, double-byte (16-bit), Unicode values, and it exposes methods for classifying the character stored in a Char variable. You can use methods like IsDigit and IsPunctuation on a Char variable to determine its type, and other similar methods can simplify your string validation code.

To use a character variable in your application, you must declare it with a statement like the following one:

Dim ch As Char = “A”

You can also initialize it by setting the variable to a character:

Dim ch As Char = CChar(“A”)

The expression “A” represents a string, even though it contains a single character. Everything you enclose in double quotes is a string. To convert it to a character, you must cast it to the Char type. If the Strict option is off (which is the default value), you need not perform the conversion explicitly.

If the Strict option is on, you must use the CChar() or CType() function to convert the string in the double quotes to a character value, as shown in the second example line. You can also pass a string to CChar() function. It will convert the first character of the string to a Char type and ignore the following characters. The CType() function can convert an object to a character.

Properties

The Char class provides two trivial properties, MaxValue and MinValue. They return the largest and smallest character values you can represent with the Char data type.

Methods

The Char data type exposes methods for handling characters. As you will see, the String and StringBuilder classes expose the Chars property, which returns individual characters in the string, and you can apply any of the methods discussed here to a variable of the Char type.

All the methods discussed in the following sections have the same syntax. They accept either a single argument, which is the character they act upon, or a string and the index of a character in the string on which they act. The IsDigit() method, for example, has two forms, which are:

Char.IsDigit(char)

Char.IsDigit(string, 3)

The first statement acts on a character variable, while the second form acts on the third character of the specified string. Both methods return True if the specified character is a numeric digit, False otherwise.

With a few exceptions, the methods of the Char class are shared. This means that you can call them without having to create an instance of the class. As you saw, the IsDigit method accepts as argument a character and doesn’t act on a Char variable. If the ch variable represents a character, you can find out whether the character is a digit with either of the following statements:

ch.IsDigit(ch)

Char.IsDigit(ch)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

532 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

The first notation isn’t very elegant, so I will use the second notation in the examples of this section. You can even use the following counter-intuitive method of calling IsDigit:

CType(“a”, Char).IsDigit(“4”)

The CType() function returns a character, and you can apply any of the System.Char class’s methods to this character.

GetNumericValue

This method returns a numeric value if called with an argument that is a digit, and the value –1 otherwise. If you call the GetNumericDigit with the argument “5”, it will return the numeric value 5. If you call it with the symbol “@”, it will return the value –1.

GetUnicodeCategory

This method returns a numeric value that is a member of the UnicodeCategory enumeration and identifies the Unicode group to which the character belongs. The Unicode categories group characters into many categories such as math symbols, currency symbols, and quotation marks. Look up the UnicodeCategory enumeration in the documentation for more information.

IsControl

This method returns a True/False value indicating whether the specified character is a control character. The Backspace and Escape keys, for example, are control characters. The second form of the method examines the character at location index in a string and returns True if it’s a control character.

IsDigit

This method determines whether the specified character is a digit. The code segment in Listing 12.1 uses the IsDigit method to find out whether the current character is a digit or a character. You can insert this code in a control’s KeyPress event to process each keystroke.

Listing 12.1: Differentiating Letter from Digit Keystrokes

Private Sub TextBox1_KeyPress(ByVal sender As Object, _

ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress Dim c As Char

c = e.KeyChar

If Char.IsDigit(c) Then

{process c as number }

Else

{process c as character or punctuation symbol } End If

End Sub

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING STRINGS AND CHARACTERS 533

The e.KeyChar property returns the character that was pressed by the user and fired the KeyPress event. To reject nonnumeric keys as the user enters text on a TextBox control, use the event handler shown in Listing 12.2.

Listing 12.2: Rejecting Nonnumeric Keystrokes

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As EventArgs) Dim c As Char

c = e.KeyChar

If Not (Char.IsDigit(c) Or Char.IsControl(c)) Then e.Handled = True

End If End Sub

This code ignores any keystrokes that don’t represent numeric digits and are not control characters. Control characters are not rejected, because we want users to be able to edit the text on the control. The Backspace key is captured by the KeyPress event, and you shouldn’t “kill” it. If the TextBox control is allowed to accept fractional values, you should allow the period character as well, by using the following If clause:

Dim c As Char c = e.KeyChar

If Not (Char.IsDigit(c) Or c = “.” Or Char.IsControl(c)) Then e.Handled = True

End If

IsLetter

This method returns a True/False value indicating whether the specified character is a letter. You can write an event handler similar to the one shown in Listing 12.2 using the IsLetter method to accept letters and reject numeric keys and special symbols.

IsLetterOrDigit

This method returns a True/False value indicating whether the specified character is a letter or a digit. The example of the Chars property of the String class shows how to scan an entire string to find out whether it’s made up of letter and digits, or whether it contains symbols as well.

IsLower, IsUpper

This method returns a True/False value indicating whether the specified character is lowercase or uppercase, respectively.

IsNumber

This method returns a True/False value indicating whether the specified character is a number. The IsNumber method takes into consideration hexadecimal digits (the characters 0123456789ABCDEF) in the same way as the IsDigit method does for decimal numbers.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com