String Manipulation

Left and Right Functions

The Left function returns the left portion of a string. The Right function returns the right portion of a string.

Syntax

Left(string, length)
Right(string, length)
string is a string variable or text inside quotes. length is the number of characters from left or right.

Look at the following example.

Example 1
Dim strText1 As String
Dim strText2 As String
strText1 = "Newark"
strText2 = "Holstein Jersey"
lblResult.Caption = Left(strText1, 3) & Right(strText2, 7)

What is the result of Example 1?

Mid Function

The Mid function returns a substring from the middle of another string.

Syntax

Mid(string, start, length)
string is a string variable or text inside quotes. start is the character position to begin taking characters. length is the number of characters to return.

Look at the following example.

Example 2
Dim strText As String
strText = "Fifteen"
lblResult.Caption = Mid(strText, 4, 3)

What is the result of Example 2?

Len Function

The Len function returns the number of characters in a string.

Syntax

Len(string)
string is a string variable or text inside quotes.

Challenge Question: How can we find the middle character in a string? Remember, some strings have an even length and some have an odd length. Try writing a section of code that will find the middle character of any word stored in strWord.

Class Exercise: String Test

Create a program that extracts the first, middle and last letter of a word.

 

  1. Begin by designing the form.
  2. Use the names txtInput, lblFirst, lblMiddle, lblLast, cmdGo, cmdDone for the controls on the form.
  3. Add code to cmdDone.
  4. Add the code for cmdGo.

String Test Code
Private Sub cmdDone_Click()
    ' end program
    Unload frmMain
End Sub

Private Sub cmdGo_Click()
‘ dimension
Dim strWord As String
Dim intMiddle As Integer
‘ get from textbox
strWord = txtInput.Text
‘ calculate middle
If Len(strWord) Mod 2 = 0 Then
‘ even number of letters
intMiddle = Len(strWord) / 2
Else
‘ odd number of letters
intMiddle = Len(strWord) \ 2 + 1
End If
‘ display results
lblFirst.Caption = Left(strWord, 1)
lblMiddle.Caption = Mid(strWord, intMiddle, 1)
lblLast.Caption = Right(strWord, 1)
End Sub

Class Exercise: String Test 2.0

Modify your program for improved error control and ease of use.

  1. Make the program display results only if the length of the input is >= 3.
  2. Add code to clear the results when the input changes.
  3. Try your program out to make sure it works.
  4. Raise your hand and ask your teacher to grade your assignment on screen.
Challenge Question: How can you create the Mid() function using only the Left() and Right() functions?

Assignment

The Count Letter assignment is due in one week.