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

534 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

IsPunctuation

This method returns a True/False value indicating whether the specified character is a punctuation mark.

IsSeparator

This method returns a True/False value indicating whether the character is categorized as a separator (space, newline character, and so on). The following characters are considered separators (oddly, the semicolon is not a separator):

)

closing parenthesis

:colon

,comma

!exclamation mark

(

opening parenthesis

. period

#pound sign

IsWhiteSpace

This method returns a True/False value indicating whether the specified character is white space. Any sequence of spaces, tabs, line feeds, and form feeds is considered white space. Use this method along with the IsPunctuation method to remove all characters in a string that are not words.

ToLower, ToUpper

These methods convert their argument to a lowercase or uppercase character and return it as another character.

ToString

This method converts a character to a string. It returns a single-character string, which you can use with other string-manipulation methods or functions.

The String Class

The String class implements the String data type, which is one of the richest data types in terms of the members it exposes. We have used strings extensively in earlier chapters, but this is a formal discussion of the String data type and all of the functionality it exposes.

To create a new instance of the String class, you simply declare a variable of the String type. You can also initialize it by assigning to the corresponding variable a text value:

Dim title As String = “Mastering VB.NET”

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING STRINGS AND CHARACTERS 535

The String class exposes a Replace method, but this method returns a new string; it doesn’t replace the specified characters in the original string:

Dim title As String = “Mastering VB.NET” Dim newTitle As String

newTitle = title.Replace(“VB”, “Visual Basic”)

The Replace method, and many other methods of the String class, don’t operate directly on a string. Instead, they create a new string and return it as their result. In the last statement of the example, the Replace method doesn’t act directly on the title variable. It creates a new String variable, which is assigned to another variable. You can also apply the result of a method to the same variable to which the method applies:

title = title.Replace(“VB”, “Visual Basic”)

You can also manipulate strings with Visual Basic’s string-manipulation functions. For example, you can replace the substring “VB” with “Visual Basic” with the following statement:

newTitle = Replace(title, “VB”, “Visual Basic”)

Like the methods of the String class, the string-manipulation functions don’t act on the original string; they return a new string.

If you plan to manipulate strings in your code often, use the StringBuilder class instead, which is extremely fast compared to the String class and VB’s string-manipulation functions.

Some of the members of the String class are shared members, while some others are instance members. The Copy method, for example, accepts as argument the string to be copied and doesn’t require an instance of the class:

Dim s1, s2 As String s1 = “This is a string” s2 = String.Copy(s1)

The Length property, however, can only be applied to an instance of the String class. The following statement returns the length of the string stored in the variable s1:

Console.WriteLine(s1 & “ is “ & s1.Length.ToString & “ characters long.”)

Properties

The String class exposes only two properties, the Length and Chars properties, which return a string’s length and its characters respectively. Both properties are read-only.

Length

The Length property returns the number of characters in the string, and it’s read-only. To find out the number of characters in a string variable, use the following statement:

chars = myString.Length

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

536 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

You can apply the Length method to any expression that evaluates to a string. The following statement formats the current date in long date format (this format includes the day’s and month’s names) and then retrieves the string’s length:

StrLen = Format(Now(), “dddd, MMMM dd, yyyy”).Length

The Format() function formats numbers and dates and was discussed in Chapter 3.

Chars

The Chars property is an array of characters that holds all the characters in the string. Use this property to read individual characters from a string based on their location in the string. The index of the first character in the Chars array is zero.

Tip The Chars array is read-only, and you can’t edit a string by setting individual characters.

The loop detailed in Listing 12.3 rejects strings (presumably passwords) that are less than six characters long and don’t contain a special symbol:

Listing 12.3: Validating a Password

Private Function ValidatePassword(ByVal password As String) As Boolean If password.Length < 6 Then

MsgBox(“The password must be at least 6 characters long”) Return False

End If

Dim i As Integer

Dim valid As Boolean = False For i = 0 To password.Length - 1

If Not Char.IsLetterOrDigit(password.Chars(i)) Then Return True Next

MsgBox(“The password must contain at least one “ & _ “character that is not a letter or a digit.”)

Return False End Function

The code checks the length of the user-supplied string and makes sure it’s at least six characters long. If not, it issues a warning and returns False. Then it starts a loop that scans all the characters in the string. Each character is accessed by its index in the string. If one of them is not a letter or digit—in which case the IsLetterOrDigit method will return False—the function terminates and returns True to indicate a valid password. If the loop is exhausted, then the password argument contains no special symbols and the function displays a message and returns False.

Methods

All the functionality of the String class is available through methods, which are described in the following sections. Most of these methods are shared methods: you must supply the string on which

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING STRINGS AND CHARACTERS 537

they act as argument. In other words, they don’t modify the current instance of the String class; instead, they return a new String value.

Compare

This method compares two strings and returns a negative value if the first string is less than the second, a positive value if the second string is less than the first, and zero if the two strings are equal. The Compare method is overloaded, and the first two arguments are always the two strings to be compared.

The simplest form of the method accepts two strings as arguments:

String.Compare(str1, str2)

The following form of the method accepts a third argument, which is a True/False value and determines whether the search will be case-sensitive (if True) or not:

String.Compare(str1, str2, case)

Another form of the Compare method allows you to compare segments of two strings; its syntax is

String.Compare(str1, index1, str2, index2, length)

index1 and index2 are the starting locations of the segment to be compared in each string. The two segments must have the same length, which is specified by the last argument.

The following statements return the values shown in bold below each:

Console.WriteLine(String.Compare(“the quick brown fox”, “THE QUICK BROWN FOX”))

-1

Console.WriteLine(String.Compare(“THE QUICK BROWN FOX”, “the quick brown fox”))

1

Console.WriteLine(String.Compare(“THE QUICK BROWN FOX”, “THE QUICK BROWN FOX”))

0

If you want to specify a case-sensitive search, append yet another argument and set it to True. The forms of the Compare method that perform case-sensitive searches may accept yet another argument, which determines the culture info.

CompareOrdinal

The CompareOrdinal method compares two strings similar to the Compare method, but it doesn’t take into consideration the current locale. This method returns zero if the two strings are the same, but a positive or negative value if they’re different. These values are not 1 and –1; the value can be anything, since it represents the numeric difference between the Unicode values of the first two characters that are different in the two strings.

Concat

This method concatenates two or more strings (places them one after the other) and forms a new string. The simpler form of the Concat method has the following syntax, and it’s equivalent to the & operator:

newString = String.Concat(string1, string2)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

538 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

This statement is equivalent to the following:

newString = string1 & string2

A more useful from of the same method concatenates a large number of strings stored in an array:

newString = String.Concat(strings)

To use this form of the method, store all the strings you want to concatenate into a string array and then call the Concat method, as shown in this code segment:

Dim strings() As String = {“string1”, “string2”, “string3”, “string4”} Dim longString As String

longString = String.Concat(strings)

If you want to separate the individual strings with special delimiters, append them to each individual string before concatenating them. Or, you can use the Join method discussed later in this section. The Concat method simply appends each string to the end of the previous one.

Copy

The Copy method copies the value of one String variable to another. Notice that the value to be copied must be passed to the method as argument. The Copy method doesn’t apply to the current instance of the String class. Most programmers will use the assignment operator and will never bother with the Copy method. The last two statements in the following sample code are equivalent:

Dim s1, s2 As String s1 = “some text”

s2 = s1

s2 = String.Copy(s1)

The following syntax will also work, because the s1 variable is an instance of the String class, but it’s awkward—almost annoying:

s2 = s1.Copy(s1)

However, the Copy method doesn’t return a copy of the string to which it’s applied. The following statement is invalid:

s2 = s1.Copy

‘ INVALID STATEMENT

EndsWith, StartsWith

These two methods return True if the string ends or starts with a user-supplied substring. The syntax of these methods is

found = str.EndsWith(string) found = str.StartsWith(string)

These two methods are equivalent to using the Left and Right functions to extract a given number of characters from the left or right end of the string. The two statements following the declaration of the name variable are equivalent:

Dim name As String = “Visual Basic.NET”

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING STRINGS AND CHARACTERS 539

If Left(name, 3) = “Vis” Then ...

If name.StartsWith(“Vis”) Then ...

Notice that the comparison performed by the StartsWith method is case-sensitive. If you don’t care about the case, you can convert both the string and the substring to uppercase, as in the following example:

If name.ToUpper.StartsWith(“VIS”) Then ...

This If clause is True regardless of the casing of the name variable.

IndexOf, LastIndexOf

These two methods locate a substring in a larger string. The IndexOf method starts searching from the beginning of the string, and the LastIndexOf method starts searching from the end of the string. Both methods return an integer, which is the order of the substring’s first character in the larger string (the order of the first character is zero).

VB6 VB.NET

The IndexOf and LastIndexOf methods are equivalent to the InStr() and InStrRev() functions of VB6.

In the following examples, ch is a Char variable, chars is an array of type Char, and str is a String variable.

To locate a single character in a string, use the following forms of the IndexOf method:

String.IndexOf(ch)

String.IndexOf(ch, startIndex)

String.IndexOf(ch, startIndex, count)

The startIndex argument is the location in the string, where the search will start, and the count argument is the number of characters that will be examined. The IndexOf method returns the location of the first instance in the string—these two methods are instance methods.

To locate a string, use the following forms of the IndexOf method:

String.IndexOf(str)

String.IndexOf(str, startIndex)

String.IndexOf(str, startIndex, count)

The last three forms of the IndexOf method search for an array of characters in the string:

String.IndexOf(chars())

String.IndexOf(chars(), startIndex)

String.IndexOf(chars(), startIndex, count)

The following statement will return the position of the string “Visual” in the text of the TextBox1 control, or –1 if the string isn’t contained in the text:

Dim pos As Integer

pos = TextBox1.Text.IndexOf(“Visual”)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

540 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

Both methods perform a case-sensitive search, taking into consideration the current locale. To make case-insensitive searches, use uppercase for both the string and the substring. The following statement returns the location of the string “visual” (or “VISUAL”, “Visual”, and even “vISUAL”) within the text of TextBox1:

Dim pos As Integer

pos = TextBox1.Text.ToUpper.IndexOf(“VISUAL”)

The expression TextBox1.Text is the text on the control, and its type is String. We apply the method ToUpper to convert the text to uppercase. The expression TextBox1.Text.ToUpper is the text on the TextBox1 control converted to uppercase, which is a string value. Finally, we apply the IndexOf method to this string to locate the first instance of the word “VISUAL.”

IndexOfAny

This method accepts as argument an array of characters and returns the first occurrence of any of the array’s characters in the string:

str.IndexOfAny(chars)

where chars is an array of characters. This method attempts to locate the first instance of any member of chars in the string. If the character is found, then its index is returned. If not, the process is repeated with the second character and so on, until an instance is found, or the array has been exhausted. If you want to locate the first delimiter in a string, call the IndexOfAny method with an array like the following:

Dim chars() As Char = {CChar(“ “), CChar(“.”), CChar(“,”), CChar(“;”)}

Dim mystring As String = “This is a short sentence”

Console.WriteLine(mystring.IndexOfAny(chars))

When the last statement is executed, the value 4 will be printed on the Output window. This is the location of the first space in the string (keep in mind that the index of the first character in the string is zero).

To locate the first number in a string, pass the nums array to the IndexOfAny method, as shown in the following example:

Dim nums() As Char = {“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “0”} mystring = “This sentence contains 36 characters” Console.WriteLine(mystring.IndexOfAny(nums))

The statements shown here will work if the Strict option is off. If this option is turned on, you must explicitly convert each number to a character with the CChar() or CType() function, as shown in the first example of this section.

Insert

The Insert method inserts one or more characters at a specified location in a string and returns the new string. The syntax of the Insert method is

newString = str.Insert(startIndex, subString)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING STRINGS AND CHARACTERS 541

startIndex is the position in the str variable, where the string specified by the second argument will be inserted. The following statement will insert a dash between the second and third characters of the string “CA93010”

Dim Zip As String = “CA93010”

Dim StateZip As String

StateZip = Zip.Insert(2, “-”)

The StateZip string variable will become “CA-93010” after the execution of these statements.

Join

This method joins two or more strings and returns a single string with a separator between the original strings. Its syntax is

newString = String.Join(separator, strings)

where separator is the string that will be used as separator and strings is an array with the strings to be joined.

If you have an array of many strings and you want to join a few of them, you can specify the index of the first string in the array and the number of strings to be joined with the following form of the Join method:

newString = String.Join(separator, strings, startIndex, count)

The following statement will create a full path by joining folder names:

Dim path As String

Dim folders() As String = {“My Documents”, “Business”, “Expenses”} path = String.Join(“/”, folders)

The value of the path variable after the execution of these statements will be:

My Documents/Business/Expenses

Split

Just as you can join strings, you can split a long string into smaller ones with the Split method, whose syntax is

strings() = String.Split(delimiters, string)

where delimiters is an array of characters and string is the string to be split. The string is split into sections that are separated by any one of the delimiters specified with the first argument. These strings are returned as an array of strings. The Split method, like the Join method, is a shared method (you can’t split a string variable by applying the Split method to it).

Note The delimiters array allows you to specify multiple delimiters, which makes it a great tool for isolating words in a text. You can specify all the characters that separate words in text (spaces, tabs, periods, exclamation marks, and so on) as delimiters and pass them along with the text to be parsed to the Split method.

The statements in Listing 12.4 isolate the parts of a path, which are delimited by a backslash character.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

542 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

Listing 12.4: Extracting a Path’s Components

Dim path As String = “c:\My Documents\Business\Expenses” Dim delimiters() As Char = {CChar(“\”)}

Dim parts() As String

parts = path.Split(delimiters) Dim iPart As IEnumerator iPart = parts.GetEnumerator While iPart.MoveNext

Console.WriteLine(iPart.Current.tostring) End While

If the path ends with a slash, then the Split method will return an extra empty string. You should either make sure that the string doesn’t start or end with a delimiter, or ignore the elements of the parts array that hold empty strings.

Notice that the parts array is declared without a size. It’s a one-dimensional array that will be dimensioned automatically by the Split method, according to the number of substrings separated by the specified delimiter(s). The second half of the code iterates through the parts of the path and displays them on the Output window.

If you execute the statements of Listing 12.4 (place them in a button’s Click event handler and run the program), the following strings will be printed in the Output window:

c:

My Documents Business Expenses

Remove

The Remove method removes a given number of characters from a string, starting at a specific location, and returns the result as a new string. Its syntax is

newString = str.Remove(startIndex, count)

where startIndex is the index of the first character to be removed in the str string variable and count is the number of characters to be removed.

The Remove method is new to VB.NET. To remove a particular number of characters in previous versions of Visual Basic, you had to build a new string by concatenating the characters to the left and to the right of the part of the string to be removed.

Replace

This method replaces all instances of a specified character (or substring) in a string with a new one. It creates a new instance of the string, replaces the characters as specified by its arguments, and returns this string:

newString = str.Replace(oldChar, newChar)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING STRINGS AND CHARACTERS 543

where oldChar is the character in the str variable to be replaced and newChar is the character to replace the occurrences of oldChar. The string after the replacement is returned as the result of the method. The following statements replace all instances of the tab character with a single space. You can change the last statement to replace tabs with a specific number of spaces—usually 3, 4, or 5 spaces.

Dim txt, newTxt As String Dim vbTab As String = vbCrLf

txt = “some text with two tabs” newTxt = txt.Replace(vbTab, “ “)

Note that the Replace method can also replace substrings in a longer string. This form of the syntax is shown next:

newString = str.Replace(oldString, newString)

Use the following statements to replace all instances of “VB7” in a string with the substring “VB.NET”:

Dim txt, newTxt As String txt = “Welcome to VB7”

newTxt = txt.Replace(“VB7”, “VB.NET”)

PadLeft, PadRight

These two methods align the string left or right in a specified field. They both return a fixed-length string with spaces to the right (for left-padded strings) or to the left (for right-padded strings). Both methods accept the length of the field as argument and return a new string:

Dim LPString, RPString As String

LPString = “[“ & “Mastering VB”.PadRight(20) & “]”

RPString = “[“ & “Mastering VB”.PadLeft(20) & “]”

After the execution of these statements, the values of the LPString and RPString variables are:

[Mastering VB

]

[Mastering VB]

There are 8 spaces to the right of the left-padded string and 8 spaces to the right of the leftpadded string.

VB6 VB.NET

The PadLeft and PadRight methods replace the LSet() and RSet() functions of VB6.

Another form of these methods allows you to specify the character to be used in padding the strings. If you change the calls to the PadLeft and PadRight methods in the last example with the following:

LPString = “Mastering VB”.PadRight(20, “@”)

RPString = “Mastering VB”.PadLeft(20, “.”)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com