Mid Function

   
Mid Function

Class

Microsoft.VisualBasic.Strings

Syntax

 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

Return Value

String

Description

Returns a substring of a specified length from a given string

Rules 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.

  • If start is less than zero, runtime error 5, "Invalid procedure call or argument," is generated.

  • If length is omitted or length is greater than the length of str , all characters from start to the end of str are returned.

Example

The following example parses the contents of a text box control (named txtString ) and writes each word to a list box (named lstWord ). Note the use of the InStr function to determine the position of either a space or a carriage return/line feed character combination the two characters that can terminate a word in this case:

 Private Sub btnParse_Click(ByVal sender As System.Object, _                            ByVal e As System.EventArgs) _             Handles btnParse.Click    Dim strString, strWord As String    Dim intStart, intEnd, intStrLen, intCrLf As Integer    Dim blnLines As Boolean    lstWords.Items.Clear(  )    intStart = 1    strString = Trim(txtString.Text)    intStrLen = Len(strString)    intCrLf = InStr(1, strString, vbCrLf)    If intCrLf Then blnLines = True    lstWords.BeginUpdate(  )    Do While intStart > 0       intEnd = InStr(intStart, strString, " ") - 1       If intEnd <= 0 Then intEnd = intStrLen       If blnLines And (intCrLf < intEnd) Then          intEnd = intCrLf - 1          intCrLf = InStr(intEnd + 2, strString, vbCrLf)          If intCrLf = 0 Then blnLines = False          lstWords.Items.Add(Mid(strString, intStart, _                                 intEnd - intStart + 1))          intStart = intEnd + 3       Else          lstWords.Items.Add(Mid(strString, intStart, _                                 intEnd - intStart + 1))          intStart = intEnd + 2       End If       If intStart > intStrLen Then intStart = 0    Loop    lstWords.EndUpdate(  ) End Sub 

Programming Tips and Gotchas

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

  • Use InStr to determine the starting point of a given substring within another string.

See Also

Left Function, Mid Function, Right Function

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

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