Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

Problem

You want to extract substrings located at the left end, the right end, or somewhere in the middle of a string.

Solution

Visual Basic 2005 strings now have a built-in method named Substring() that provides an alternative to the traditional Visual Basic functions Left(), Mid(), and Right(), although the language retains these features if you wish to use them. To emulate each of these functions, set the Substring() method's parameters appropriately. The following code shows how to do this:

Dim quote As String = "The important thing is not to " & _ "stop questioning. --Albert Einstein" ' ----- Left(quote, 3) … "The" MsgBox(quote.Substring(0, 3)) ' ----- Mid(quote, 5, 9) … "important" MsgBox(quote.Substring(4, 9)) ' ----- Mid(quote, 58) … "Einstein" MsgBox(quote.Substring(57)) ' ----- Right(quote, 8) … "Einstein" MsgBox(quote.Substring(quote.Length - 8))

Discussion

Each line of code in the sample is prefaced by a comment line showing the equivalent syntax from VB 6. One of the big differences apparent in these examples is that the first character in the string is now at offset position 0 instead of 1, requiring a change in the offsets supplied to the Substring() method. The lengths of the sub-strings are still the same.

Категории