Changes

Jump to: navigation, search

Working with Strings in Visual Basic

2,536 bytes added, 14:38, 2 August 2007
Extracting Text from Anywhere in a String
strMidString = Mid("Visit Paris today", 7, 5 )
</pre>
 
== Searching for a Substring ==
 
It is quite common to need to search a string for the occurrence of another string (otherwise known as a ''substring''). To find out if a string contains a particular substring in Visual Basic we use the ''Instr()'' function.
 
The Visual Basic ''Instr()'' function accepts one optional, and two mandatory parameters. The function is a little odd in that it is the first parameter which is optional (most other function always make the first parameter mandatory). The syntax for using ''Instr()'' is as follows:
 
'''Instr([''start position'', ''string'', ''substring'' ''')'''
 
The parameters accepted by ''Intr()'' are as follows:
 
* '''start position''' - (Optional) Dictates where in the string to begin the search. If this parameter is omitted the search begins from the start of the string.
 
* '''string''' - The string literal or string variable in which the search is to be performed
 
* '''substring''' - The substring for which to search
 
If a match to the substring is found, ''Instr()'' returns the character location of the start of the substring. If no match is found, the function returns 0.
 
The following Visual Basic code excerpt uses ''Instr()'' to locate the first instance of a space character and then uses the ''Mid()'' function to extract the rest of the string thereby extracting the last name from the person's full name:
 
<pre>
Dim strFullName As String = "John Smith"
Dim strLastName As String
 
strLastName = Mid( StrFullName, Instr(strFullName, " "))
</pre>
 
== Trimming Leading and Trailing Spaces from a String ==
 
In the above example you may have noticed that the Mid() function returned us the last name of the customer, but also extracted the space character. It is extremely common when handling strings in Visual Basic to find that either leading or trailing spaces need to be cropped from a string. To address this need, Visual Basic provides the following three functions. All three functions take as a single parameter the string to be trimmed and return the modified string:
 
* '''Trim()''' - Removes all spaces from the beginning and end of the specified string.
 
* '''LTrim()''' - Removes all spaces from the beginning of the specified string.
 
* '''RTrim()''' - Removes all spaces from the end of the specified string.
 
Using the ''Trim()'' function we can now remove the leading space from our previous example:
 
<pre>
Dim strFullName As String = "John Smith"
Dim strLastName As String
 
strLastName = Trim ( Mid( StrFullName, Instr(strFullName, " ")) )
</pre>

Navigation menu