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
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
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
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.
- Begin by designing the form.
- Use the names
txtInput, lblFirst, lblMiddle, lblLast, cmdGo, cmdDone
for the controls on the form. - Add code to
cmdDone
. - Add the code for
cmdGo
.
String Test Code |
Private Sub cmdDone_Click() ' end program Unload frmMain End Sub Private Sub cmdGo_Click() |
Class Exercise: String Test 2.0
Modify your program for improved error control and ease of use.
- Make the program display results only if the length of the input is >= 3.
- Add code to clear the results when the input changes.
- Try your program out to make sure it works.
- 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.