6.3 Selecting Part of a String

advertisement
6.3 Selecting Part of a String
Suppose you want to take a few letters out of one string and join them with a few letters from
another string. Or, maybe you want to output each letter of a string one at a time. The Mid
function returns a specified number of characters (a substring) from a string. Type the following
activity into the Form_Load and write down the result. Try to make a conclusion about Mid.
Activity 6.3.1
Dim Hello As String, Word1 As String, Word2 As String, Word3 As String
Hello = " I love Visual Basic"
Word1 = Mid(Hello, 1,6)
Word2 = Mid(Hello, 8, 1)
Word3 = Mid(Hello, 15,1)
MsgBox Word1 & " " & Word2 & " " & Word3
The syntax for the Mid function is:
Mid(string, start, length) where string is the string you are dissecting, start is the character to
start at and length is the number of characters to select.
Word1 = I love
Word2 = V
Word3 = B
If you omit the length, then the rest of the string will be output. For example:
Word3 = Mid(Hello, 15) would give Word3 the value Basic since B is the 15 letter and no length
is given.
Activity 6.3.2
Type in the following and record your result:
Dim Hello As String
Dim Num As Integer 'counter for the loop
Hello = "I love Visual Basic"
For Num = 1 to Len(Hello)
MsgBox Mid(Hello, Num, 1)
Next Num
This should go through the letters in the string one by one and output them on the screen.
Len(string) is a function that returns the number of characters and spaces in a string. For
example, Len(Hello) is 19.
Download