Another useful string method is Substring. This allows you to grab one string within another. (For example, if you wanted to grab the ".com" from the email address "firstname.lastname@example.org")
In between the round brackets of Substring( ), you specify a starting position, and then how many characters you want to grab (the count starts at zero again). Like this:
Dim Email as String
Dim DotCom as String
Email = "email@example.com"
DotCom = Email.Substring( 5, 4 )
The message box would then display the characters grabbed from the string, in this case the ".com" at the end (start at position 5 in the string and grab 4 characters).
You could also do a check to see if an email address ended in ".com" like this:
Dim Email As String
Dim DotCom As String
Email = "firstname.lastname@example.org"
DotCom = Email.Substring( Email.Length - 4, 4 )
If DotCom = ".com" Then
MessageBox.Show("Ends in Dot Com")
MessageBox.Show("Doesn't End in Dot Com")
The starting position for Substring( ) this time is "Email.Length - 4". This is the length of the string variable called Email, minus 4 characters. The other 4 means "grab four characters"
You have to be careful, though. If there wasn't four characters to grab, VB would give you an error message.
We could replace the Chars() For loop code we wrote earlier with a Substring() method. The result would be the same. Here's the code:
For i = 0 To TextLength - 1
OneCharacter = FirstName.Substring(
i, 1 )
So we're saying, "Start grabbing characters from the position i. Just grab one character".
Substring and Chars are very useful methods to use when you want to check the letters in a string of text.
In the next part, we'll take a look at the Equals, Replace, and Insert Methods.