Learning the Visual Basic .NET Language - The String Class
(Page 6 of 9 )
One of the best examples of how class members can replace built-in functions is found with strings. You might be familiar with the standard Visual Basic string functions such as Len(), Left(), Right(), and Instr(). These functions have been a part of Visual Basic and VBScript for years, and they’re still available in VB .NET. However, a better solution is to use the methods of the String class, which provides greater consistency between .NET languages.
The following code snippet shows several ways to manipulate a string using its object nature.
Dim MyString As String = "This is a test string "
MyString = MyString.Trim() ' = "This is a test string"
MyString = MyString.Substring(0, 4) ' = "This"
MyString = MyString.ToUpper() ' = "THIS"
MyString = MyString.Replace("IS", "AT") ' = "THAT"
Dim Length As Integer = MyString.Length ' = 4
The first few statements use built-in methods, like Trim(), Substring(), ToUpper(), and Replace(). These methods generate new strings, and each of these statements replaces the current MyString with the new string object. The final statement uses a built-in Length property, which returns an integer that represents the number of letters in the string.
TIP A method is just a function or procedure that’s hard-wired into an object. A property is similar to a variable—it’s a piece of data that’s associated with an object. You’ll learn more about methods and properties in the next chapter.
Note that the Substring() method requires a starting offset and a character length. Strings use zero-based counting. That means that the first letter is in position 0, the second letter is in position 1, and so on. This marks a sharp change from the traditional Visual Basic functions, which used one-based counting. This change is found throughout the .NET Framework for the sake of consistency.
You can even use these methods in succession in a single (rather ugly) line:
MyString = MyString.Trim.SubString(0, 4).ToUpper().Replace("IS", "AT")
Or, to make life more interesting, you can use the string methods on string literals just as easily as string variables:
MyString = "hello".ToUpper() ' Sets MyString to "HELLO"
Table 3-3 lists some useful members of the System.String class.
Table 3-3. Useful String Members
Member | Description |
Length | Returns the number of characters in the string (as an integer). |
ToUpper() and ToLower() | Changes the string to contain all uppercase or all lowercase characters. |
Trim(), TrimEnd(), and TrimStart() | Removes spaces or some other characters from either (or both) ends of a string. |
PadLeft() and PadRight() | Adds the specified character to either side of a string, the number of times you indicate. For example, PadLeft(3, " ") adds three spaces to the left side. |
Insert() | Puts another string inside a string at a specified (zero-based) index position. For example, Insert(1, "pre") adds the string "pre" after the first character of the current string. |
Remove() | Removes a specified number of strings from a specified position. For example, Remove(0, 1) removes the first character. |
| Replace() | Replaces a specified substring with another string. For example, Replace("a", "b") changes all "a" characters in a string into "b" characters. |
Substring() | Extracts a portion of a string of the specified length at the specified location. For example, Substring(0, 2) retrieves the first two characters. |
StartsWith() and EndsWith() | Determines whether a string ends or starts with a specified substring. For example, StartsWith("pre") will return either True or False, depending on whether the string begins with the letters "pre" in lowercase. |
|
Table 3-3. Useful String Members (Continued)
Member | Description |
IndexOf() and LastIndexOf() | Finds the zero-based position of a substring in a string. This returns only the first match, and can start at the end or beginning. YOu can also use overloaded versions of these methods that accept a parameter that specifies the position to start the search. |
Split() | Divides a string into an array of substrings delimited by a specific substring. For example, with Split(".") you could chop a paragraph into an array of sentence strings. |
Join() | Joins an array of strings together. You can also specify a separator that will be inserted between each element. |
|
The DateTime and TimeSpan Classes
The DateTime and TimeSpan data types also have built-in methods and properties. These class members allow you to perform the following three useful tasks:
- Extract a part of a DateTime (for example, just the year), or convert a TimeSpan to a specific representation (such as the total number of days or total number of minutes).
- Easily perform date calculations.
- Determine the current date and time and other information (such as the day of the week or whether or not the date occurs in a leap year).
For example, the following block of code creates a DateTime object, sets it to the current date and time, and adds a number of days. It then creates a string that indicates the year that the new date falls in (“for example, “2003”).
Dim MyDate As DateTime = DateTime.Now
MyDate = MyDate.AddDays(365)
Dim DateString As String = MyDate.Year.ToString()
The next example shows how you can use a TimeSpan object to find the total number of minutes between two DateTime objects.
Dim MyDate1 As DateTime = DateTime.Now
Dim MyDate2 As DateTime = DateTime.Now.AddHours(3000)
Dim Difference As TimeSpan
Difference = MyDate2.Subtract(MyDate1)
Dim NumberOfMinutes As Double NumberOfMinutes = Difference.TotalMinutes
These examples give you an idea of the flexibility .NET provides for manipulating date and time data. Tables 3-4 and 3-5 list some of the more useful built-in features of the DateTime and TimeSpan objects.
Table 3-4. Useful DateTime Members
Member | Description |
Now | Gets the current date and time. |
Today | Gets the current date, and leaves time set to 00:00:00. |
Year, Date, Day, Hour, Minute, Second, and Millisecond | Returns one part of the DateTime object as an integer. For example, Month will return 12 for any day in December. |
DayOfWeek | Returns an enumerated value that indicates the day of the week for this DateTime, using the DayOfWeek enumeration. For example, if the date falls on Sunday, this will return DayOfWeek.Sunday. |
| Add() and Subtract() | Adds or subtracts a TimeSpan from the DateTime. |
AddYears(), AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds(), AddMilliseconds() | Adds an integer that represents a number of years, months, and so on, and returns a new DateTime. You can use a negative integer to perform a date subtraction. |
DaysInMonth() | Returns the number of days in the month represented by the current DateTime. |
IsLeapYear() | Returns True or False depending on whether the current DateTime is in a leap year. |
ToString() | Changes the current DateTime to its string representation. You can also use an over-loaded version of this method that allows you to specify a parameter with a format string. |
|
Table 3-5. Useful TimeSpan Members
Member | Description |
Days, Hours, Minutes, Seconds, Milliseconds | Returns one component of the current TimeSpan. For example, the Hours property can return an integer from 0 to 23. |
TotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds | Returns teh total value of the current TimeSpan, indicated as a number of days, hours, minutes, and so on. For example, the TotalDays property might return a number like 234.342. |
Add() and Subtract() | Combines TimeSpan objects together. |
FromDays(), FromHours(), FromMinutes(), FromSeconds(), FromMilliseconds() | Allows you to quickly specify a new TimeSpan. For example, you can use TimeSpan.FromHours(24) to define a TimeSpan object exactly 24 hours long. |
ToString() | Changes the current TimeSpan to its string representation. You can also use an over-loaded version of this method that allows you to specify a parameter with a format string. |
| |
The Array ClassArrays also behave like objects in the new world of .NET. For example, if you want to find out the size of an array, you won’t use the old-fashioned UBound() function that’s built into the Visual Basic language. Instead, you can use the Array.GetUpperBound() method in any language. The following code snippet shows this technique in action.
Dim MyArray() As Integer = {1, 2, 3, 4, 5} Dim Bound As Integer
' Zero represents the first dimension of an array.
Bound = MyArray.GetUpperBound(0) ' Bound = 4
Arrays also provide a few other useful methods, which allow you to sort them, reverse them, and search them for a specified element. Table 3-6 lists some useful members of the System.Array class.
Table 3-6. Useful Array MembersMember | Description |
Length | Returns an integer that represents the total number of elements in all dimensions of an array. For example, a 3 × 3 array has a length of 9. |
GetLowerBound() and GetUpperBound() | Determines the dimensions of an array. As with just about everything in .NET, you start counting at zero (which represents the first dimension). |
Clear() | Empties an array’s contents. |
IndexOf() and LastIndexOf() | Searches a one-dimensional array for a specified value and returns the index number. You cannot use this with multidimensional arrays. |
Sort() | Sorts a one-dimensional array made up of comparable data such as strings or numbers. |
Reverse() | Reverses a one-dimensional array so that its elements are backward, from last to first. |
Next: Conditional Structures >>
More Visual Basic.NET Articles
More By Apress Publishing
|
This article is excerpted from chapter three of the book Beginning ASP.NET in VB.NET: From Novice to Professional, written by Matthew MacDonald (Apress, 2004; ISBN: 1590592786). Check it out at your favorite bookstore today. Buy this book now.
|
|