Mid Function |
Microsoft.VisualBasic.Strings
Mid( str , start [, length ])
The expression from which to return a substring
The starting position of the substring
The length of the substring
String
Returns a substring of a specified length from a given string
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.
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
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.
Left Function, Mid Function, Right Function