Mid Function


Mid Function

Class

Microsoft.VisualBasic.Strings

Syntax

     Dim result = String = Mid(str, start[, length]) 


str (required; String)

The expression from which to return a substring


start (required; Long)

The starting position of the substring


length (optional; Long)

The length of the substring to extract

Description

The Mid function returns a substring of a specified length from a given string.

Usage at a Glance

  • If str contains Nothing, Mid returns Nothing.

  • If start is greater than the length of str, a zero-length string is returned. An error occurs if start is less than zero.

  • If length is omitted, or if selecting length characters would exceed the length of the string, all characters from start to the end of str are returned.

  • Use the Len function to determine the total length of str.

  • The Mid function corresponds to the String data type's Substring method. In the following code, the two assignments to the twoOnly variable are identical.

         Dim twoOnly As String     Dim threeNumbers As String = "One Two Three"     twoOnly = Mid(threeNumbers, 5, 3)     twoOnly = threeNumbers.Substring(4, 3) 

    The Substring method uses a zero-based index to determine the starting position of the substring.

Example

The following example extracts the final directory name from a file path. For instance, in the path c:\folder1\folder2\file.txt, the function returns "folder2."

     Public Function FinalDirectory(ByVal filePath As String) As String        ' ----- Return the last directory name.        Dim lastSlash As Integer        Dim nextSlash As Integer        ' ----- Check for missing data.        If (Trim(filePath) = "") Then Return ""        ' ----- Don't accept UNC paths.        If (VisualBasic.Left(filePath, 1) = "\") Then Return ""        ' ----- Find the slashes that surround the directory.        lastSlash = InStrRev(filePath, "\")        nextSlash = InStrRev(filePath, "\", lastSlash - 1)        If (nextSlash = 0) Then Return ""        ' ----- Extract and return the name.        Return Mid  (filePath, nextSlash + 1, lastSlash - nextSlash - 1)     End Function 

See Also

Left Function, Mid Function, Right Function




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net