String Handling Functions
VB.NET provides a rich set of functionality for working with strings, both in terms of "native .NET" methods as well as the
functions found in the Microsoft.VisualBasic namespace, which will look familiar to classic VB (pre-.NET) programmers. This
article presents both the native .NET methods and the MS.VB namespace functions for string-handling. Where equivalent
functionality exists between the two methodologies, the description, syntax, and examples are presented side-by-side for easy
comparison.
Getting a String's Length
Microsoft.VisualBasic
Namespace Function
Function / Property
Name:
Description:
Syntax:
Example:
Len
Length
Returns an integer containing the length of the
specified string.
Returns an integer containing the length of the
specified string.
Len(string)
String.Length
Where string is the string whose length
(number of characters) is to be returned.
Where string is the string whose length (number of
characters) is to be returned.
intLen = Len("Visual Basic")
' intLen now has the value 12
intLen = "Visual Basic".Length
' intLen now has the value 12
Getting Parts of a String (Substrings)
Microsoft.VisualBasic
Namespace Function
Function / Method
Name:
Description:
Syntax:
VB.NET
Property
Mid
VB.NET
Method
Substring
Returns a substring containing a specified
number of characters from a string.
Returns a substring containing a specified number
of characters from a string.
Mid(string, start[, length])
String.Substring(start, length)
The Mid function syntax has these parts:
start
Part
string
Description
Required. String expression from which
characters are returned.
start
Required; Integer. Character position in
string at which the part to be taken
begins. If start is greater than the
number of characters in string, Mid
returns a zero-length string ("").
Required; Integer. Character position in
string at which the part to be taken
begins. If start is greater than or equal to
the number of characters in string,
Substring throws an exception.
length Optional; Integer. Number of characters to
return. If omitted all characters from the
start position to the end of the string are
returned.
length Optional; Integer. Number of characters
to return. If omitted or if there are fewer
than length characters in the text
(including the character at start), all
characters from the start position to the
end of the string are returned.
Example:
strSubstr = Mid("Visual Basic", 3, 4)
' strSubstr now contains "sual"
NOTE: The Mid function is one-based (i.e., the
first position of a string is 1).
NOTE:
Mid can also be used on the left side of an
assignment statement, where you can replace a
substring within a string. (When Mid is used in
this manner, it is referred to as the "Mid
statement" rather than the "Mid function".)
Example:
strTest = "Visual Basic"
strSubstr = "Visual Basic".Substring(2,
4)
' strSubstr now contains "sual"
NOTE: The Substring method is zero-based (i.e.,
the first position of a string is 0).
Mid(strTest, 3, 4) = "xxxx"
' strTest now contains "Vixxxx Basic"
Microsoft.VisualBasic
Namespace Function
Function / Method
Name:
VB.NET
Method
Left
(NOTE: The Left function must be qualified with
the Microsoft.VisualBasic namespace
because Left is also a property in the
Windows.Forms.Form namespace.)
Description:
Returns a substring containing a specified
number of characters from the beginning (left
side) of a string.
Syntax:
Left(string, length)
(use Substring)
The Left function syntax has these parts:
Part
string
Description
Required. String expression from which
the leftmost characters are returned.
length Required; Integer. Numeric expression
indicating how many characters to
return. If 0, a zero-length string ("") is
returned. If greater than or equal to the
number of characters in string, the entire
string is returned.
Example:
strSubstr = _
Microsoft.VisualBasic.Left _
("Visual Basic", 3)
' strSubstr now contains "Vis"
NOTE: The Left function is one-based (i.e., the
first position of a string is 1).
strSubstr = "Visual Basic".Substring(0,
3)
' strSubstr now contains "Vis"
REMINDER: The Substring method is zero-based
(i.e., the first position of a string is 0).
' Note that the same thing could be
' accomplished with Mid:
strSubstr = Mid("Visual Basic", 1, 3)
Microsoft.VisualBasic
Namespace Function
Function / Method
Name:
VB.NET
Method
Right
(NOTE: The Right function must be qualified
with the Microsoft.VisualBasic namespace
because Right is also a property in the
Windows.Forms.Form namespace.)
Description:
Returns a substring containing a specified
number of characters from the end (right side) of
a string.
Syntax:
Right(string, length)
The Right function syntax has these parts:
Part
string
Description
Required. String expression from which
the rightmost characters are returned.
length Required; Integer. Numeric expression
indicating how many characters to
return. If 0, a zero-length string ("") is
returned. If greater than or equal to the
number of characters in string, the entire
(use Substring)
string is returned.
Example:
strSubstr = _
Microsoft.VisualBasic.Right _
("Visual Basic", 3)
' strSubstr now contains "sic"
NOTE: The Right function is one-based (i.e., the
first position of a string is 1).
strSubstr = "Visual Basic".Substring(9,
3)
' strSubstr now contains "sic"
REMINDER: The Substring method is zero-based
(i.e., the first position of a string is 0).
' Note that the same thing could be
' accomplished with Mid:
strSubstr = Mid("Visual Basic", 10, 3)
Getting a Specific Character of a String with the Chars Property
To get a specific character of a string, you can use the Chars property, which will return the character found at the position
specified by a number (called an index) in parentheses. The position is zero-based, so the first position of the string is 0.
Example:
Dim chrTheChar As Char
Dim strTest As String = "Visual Basic"
chrTheChar = strTest.Chars(7)
' chrTheChar now contains "B"
It is also legal syntax to omit the ".Chars" part. If omitted, the Chars method will be assumed, as in the example below:
Dim chrTheChar As Char
Dim strTest As String = "Visual Basic"
chrTheChar = strTest(2)
' chrTheChar now contains "s"
Testing the Beginning and Ending Parts of a String with StartsWith and EndsWith
If you want to test whether or not a string begins with a certain combination of characters, you can use the StartsWith method,
which returns a Boolean True or False value indicating whether or not the string being tested starts with the characters given as
the argument. Therefore:
If strTest.StartsWith("Vis") Then ...
is equivalent to:
If strTest.Substring(0, 3) = "Vis" Then ...
or:
If Microsoft.VisualBasic.Left(strTest, 3) = "Vis" Then ...
If you want to test whether or not a string ends with a certain combination of characters, you can use the EndsWith method,
which returns a Boolean True or False value indicating whether or not the string being tested ends with the characters given as
the argument. Therefore:
If strTest.EndsWith("ic") Then ...
is equivalent to:
If strTest.Substring(10, 2) = "ic" Then ...
or:
If Microsoft.VisualBasic.Right(strTest, 2) = "ic" Then ...
Finding One String Within Another
Microsoft.VisualBasic
Namespace Function
Function / Method
Name:
Description:
VB.NET
Method
Instr
IndexOf
Returns an integer specifying the position of
one string within another. The search starts
either at the first character position or at the
position specified by the start argument, and
proceeds forward toward the end of the string
(stopping when either string2 is found or when
the end of the string1 is reached). If the string is
not found, 0 is returned.
Returns an integer specifying the position of one
string within another. The search starts either at
the first character position or at the position
specified by the startindex argument, and
proceeds forward toward the end of the string
(stopping when either string is found or when the
end of the string being searched is reached). If the
string is not found, -1 is returned. IndexOf
performs a case-sensitive search.
Syntax:
InStr
([start,] string1, string2 [, compare])
String.IndexOf(string [, startindex])
string
String expression sought.
startindex
Optional. Numeric expression that
sets the starting position for each
search. If omitted, search begins at the
first character position.
The InStr function syntax has these parts:
Part
Description
start
Optional. Numeric expression that
sets the starting position for each
search. If omitted, search begins at
the first character position. The
start argument is required if
compare is specified.
string1
Required. String expression being
searched.
string2
Required. String expression sought.
compare
Optional; numeric. A value of 0 (the
default) specifies a binary (casesensitive) search. A value of 1
specifies a textual (caseinsensitive) search.
NOTE: The CompareMethod enumeration can
be specified for the compare argument: for 0
(case-sensitive), CompareMethod.Binary is
used; for 1 (case-insensitive),
CompareMethod.Text is used. Alternatively,
the older "vb" constants vbBinaryCompare
and vbTextCompare can be used for 0 and 1
respectively.
NOTE: If the optional compare argument is
specified, then the start argument must also be
specified.
Example:
intPos = Instr("Visual Basic", "a")
' intPos now has the value 5
' (search started at position 1
' by default and is case-sensitive
' by default)
intPos = "Visual Basic".IndexOf("a")
' intPos now has the value 4
intPos = Instr(6, "Visual Basic", "a")
' intPos now has the value 9
' (search started at position 6
' and is case-sensitive by default)
intPos = "Visual Basic".IndexOf("A")
' intPos now has the value -1
intPos = Instr("Visual Basic", "A")
' intPos now has the value 0
' (case-sensitive search was performed
' by default)
intPos = "Visual Basic".IndexOf("a", 6)
' intPos now has the value 8
NOTE: The IndexOf method is zero-based (i.e.,
the first position of a string is 0).
intPos = Instr(1, "Visual Basic", _
"A", 1)
- or
intPos = Instr(1, "Visual Basic", _
"A", CompareMethod.Text)
' intPos now has the value 5
' (search started at position 1 and is
' case-insensitive)
NOTE: The Instr function is one-based (i.e., the
first position of a string is 1).
Function / Method
Name:
Microsoft.VisualBasic
Namespace Function
VB.NET
Method
InstrRev
LastIndexOf
Description:
Returns an integer specifying the position of
one string within another. The search starts
either at the last character position or at the
position specified by the start argument, and
proceeds backward toward the beginning of the
string (stopping when either string2 is found or
when the beginning of the string1 is reached). If
the string is not found, 0 is returned.
Returns an integer specifying the position of one
string within another. The search starts either at
the last character position or at the position
specified by the startindex argument, and
proceeds backward toward the beginning of the
string (stopping when either string is found or
when the beginning of the string being searched is
reached). If the string is not found, -1 is returned.
LastIndexOf performs a case-sensitive search.
Syntax:
InStrRev
(string1, string2[, start, [,
compare]])
String.LastIndexOf(string [, startindex])
string
String expression sought.
The InStrRev function syntax has these parts:
startindex
Optional. Numeric expression that
sets the starting position for each
search. If omitted, search begins at the
last character position.
Part
Description
string1
Required. String expression being
searched.
string2
Required. String expression sought.
start
Optional. Numeric expression that
sets the starting position for each
search. If omitted, search begins at
the last character position.
compare
Optional; numeric. A value of 0 (the
default) specifies a binary (casesensitive) search. A value of 1
specifies a textual (caseinsensitive) search.
NOTE: The CompareMethod enumeration can
be specified for the compare argument: for 0
(case-sensitive), CompareMethod.Binary is
used; for 1 (case-insensitive),
CompareMethod.Text is used. Alternatively,
the older "vb" constants vbBinaryCompare
and vbTextCompare can be used for 0 and 1
respectively.
Example:
intPos = InstrRev("Visual Basic", "a")
' intPos now has the value 9
' (search started at last position
' by default and is case-sensitive
' by default)
intPos = InstrRev("Visual Basic", _
"a", 6)
' intPos now has the value 5
' (search started at position 6
' and is case-sensitive by default)
intPos = InstrRev("Visual Basic", "A")
' intPos now has the value 0
' (case-sensitive search was performed
' by default)
lngPos = InstrRev("Visual Basic", _
"A", , 1)
' intPos now has the value 9
' (search started at last position
' and is case-insensitive)
' Note that this example has a
' placeholder for the optional
' start argument.
NOTE: The InstrRev function is one-based (i.e.,
the first position of a string is 1).
intPos = "Visual Basic".LastIndexOf("a")
' intPos now has the value 8
intPos = _
"Visual Basic".LastIndexOf("a", 6)
' intPos now has the value 4
intPos = "Visual Basic".LastIndexOf("A")
' intPos now has the value -1
NOTE: The LastIndexOf method is zero-based
(i.e., the first position of a string is 0).
Testing to See If One String is Contained Within Another with Contains
If you want to test whether or not one string is contained within another, you can use the Contains method, which returns a
Boolean True or False value indicating whether or not the string being tested contains the characters given as the argument.
Therefore:
If strTest.Contains("asi") Then ...
is equivalent to:
If strTest.IndexOf("asi") <> -1 Then ...
or:
If Instr(strTest, "asi") > 0 Then ...
Replacing Text Within a String
Microsoft.VisualBasic
Namespace Function
Function / Method
Name:
Description:
Syntax:
Replace
VB.NET
Method
Replace
Returns a string in which a specified substring
has been replaced with another substring a
specified number of times.
Returns a string in which all occurrences of a
specified substring has been replaced with another
substring.
Replace (expression, find, replacewith
[, start[, count[, compare]]])
String.Replace(oldstring, newstring)
oldstring
Required. Substring being
searched for.
newstring
Required. Replacement substring.
The Replace function syntax has these parts:
Part
expression
find
Description
Required. String expression
containing substring to replace.
Required. Substring being
searched for.
replacewith
Required. Replacement
substring.
start
Optional. Position within
expression where substring
search is to begin. If omitted, 1
is assumed.
count
Optional. Number of substring
substitutions to perform. If
omitted, the default value is 1,
which means make all possible
substitutions.
compare
Optional. Numeric value
indicating the kind of
comparison to use when
evaluating substrings. (0 =
case sensitive, 1 = caseinsensitive)
NOTE: The CompareMethod enumeration can
be specified for the compare argument: for 0
(case-sensitive), CompareMethod.Binary is
used; for 1 (case-insensitive),
CompareMethod.Text is used. Alternatively,
the older "vb" constants vbBinaryCompare
and vbTextCompare can be used for 0 and 1
respectively.
Example:
strNewDate = _
Replace("08/31/2001", "/", "-")
' strNewDate now contains "08-31-2001"
strNewDate = _
"08/31/2001".Replace("/", "-")
' strNewDate now contains "08-31-2001"
Casing Strings
Microsoft.VisualBasic
Namespace Function
Function / Method
Name:
Description:
VB.NET
Method
UCase
ToUpper
Converts all lowercase letters in a string to
uppercase. Any existing uppercase letters and
non-alpha characters remain unchanged.
Converts all lowercase letters in a string to
uppercase. Any existing uppercase letters and
non-alpha characters remain unchanged.
Syntax:
UCase(string)
String.ToUpper
Example:
strNew = UCase("Visual Basic")
' strNew now contains "VISUAL BASIC"
strNew = "Visual Basic".ToUpper
' strNew now contains "VISUAL BASIC"
Function / Method
Name:
Description:
Microsoft.VisualBasic
Namespace Function
VB.NET
Method
LCase
ToLower
Converts all uppercase letters in a string to
lowercase. Any existing lowercase letters and
non-alpha characters remain unchanged.
Converts all uppercase letters in a string to
lowercase. Any existing lowercase letters and nonalpha characters remain unchanged.
Syntax:
LCase(string)
String.ToLower
Example:
strNew = LCase("Visual Basic")
' strNew now contains "visual basic"
strNew = "Visual Basic".ToLower
' strNew now contains "visual basic"
Trimming Strings
Microsoft.VisualBasic
Namespace Function
VB.NET
Method
Function / Method
Name:
Description:
Removes leading blank spaces from a string.
Removes leading blank spaces from a string.
Syntax:
LTrim(string)
String.TrimStart
Example:
strTest = LTrim(" Visual Basic ")
' strTest now contains "Visual Basic
LTrim
TrimStart
"
strTest = " Visual Basic ".TrimStart
' strTest now contains "Visual Basic "
Microsoft.VisualBasic
Namespace Function
VB.NET
Method
RTrim
TrimEnd
Function / Method
Name:
Description:
Removes trailing blank spaces from a string.
Removes trailing blank spaces from a string.
Syntax:
RTrim(string)
String.TrimEnd
Example:
strTest = RTrim(" Visual Basic ")
' strTest now contains " Visual Basic"
strTest = " Visual Basic ".TrimEnd
' strTest now contains " Visual Basic"
Function / Method
Name:
Description:
Microsoft.VisualBasic
Namespace Function
VB.NET
Method
Trim
Trim
Removes both leading and trailing blank
spaces from a string.
Removes both leading and trailing blank spaces
from a string.
Syntax:
Trim(string)
String.Trim
Example:
strTest = Trim(" Visual Basic ")
' strTest now contains "Visual Basic"
strTest = " Visual Basic ".Trim
' strTest now contains "Visual Basic"
More VB.NET String-Handling Methods
Method Name:
Concat
Description:
Concatenates two or more strings together. This can be used as an alternative to the + or & operators.
Syntax:
String.Concat(string1, string2, ... stringn)
Example:
The following three statements are all equivalent:
strTest = String.Concat("Hello ", "World")
strTest = "Hello " & "World"
strTest = "Hello " + "World"
Method Name:
Insert
Description:
Inserts characters into a string
Syntax:
String.Insert(startindex, value)
Example:
startindex
Required. The (zero-based) position at which to insert characters.
value
Required. The string of characters to insert.
strTest = "The time now."
strTest = strTest.Insert(9, "is ")
' strTest now contains "The time is now."
Method Name:
Remove
Description:
Removes characters from a string
Syntax:
String.Remove(startindex [, count])
Examples:
startindex
Required. The (zero-based) position at which to delete characters.
count
Optional. The number of characters to delete. If omitted, all characters from startindex
to the end of the string will be deleted.
strTest = "Two hundred dollars."
strTest = strTest.Remove(4, 8)
' strTest now contains "Two dollars."
strTest = strTest.Remove(3)
' strTest now contains "Two"
Method Name:
Description:
Padding Strings
PadLeft
Returns a string that is right-aligned and padded on the left with spaces (or other specified character)
so that the length of the string is the specified width.
Syntax:
String.PadLeft(totalWidth [, paddingChar])
totalWidth
Required. The total number of characters to be contained in the resulting string.
paddingChar
Optional. The character to pad the string with. If omitted, a blank space will be used.
Example:
strName = "John Doe"
strNewName = strName.PadLeft(15)
' strNewName now contains "
John Doe"
strNewName = strName.PadLeft(15, "*")
' strNewName now contains "*******John Doe"
Method Name:
Description:
PadRight
Returns a string that is left-aligned and padded on the right with spaces (or other specified character)
so that the length of the string is the specified width.
Syntax:
String.PadRight(totalWidth [, paddingChar])
totalWidth
Required. The total number of characters to be contained in the resulting string.
paddingChar
Example:
Optional. The character to pad the string with. If omitted, a blank space will be used.
strName = "John Doe"
strNewName = strName.PadRight(15)
' strNewName now contains "John Doe
"
strNewName = strName.PadRight(15, "*")
' strNewName now contains "John Doe*******"
String Object
(NOTE: This can be used as an equivalent to the String function found in pre-.NET versions of Visual Basic)
Description:
Can be used to return a string containing a repeating character string of the length specified.
Syntax:
New String(character, count)
character
The character to be repeated.
count
Examples:
The number of characters to pad the string with.
strTest = New String("*", 5)
' strTest now contains "*****"
More Microsoft.VisualBasic Namespace String-Handling Functions
Function Name:
StrReverse
Description:
Returns a string in which the character order of a specified string is reversed.
Syntax:
StrReverse (string)
Examples:
strTest = StrReverse ("Visual Basic")
' strTest now contains "cisaB lausiV"
Function Name:
Space
Description:
Returns a string containing the specified number of blank spaces.
Syntax:
Space(number)
Where number is the number of blank spaces desired.
Examples:
strTest = Space(5)
' strTest now contains "
"
Function Name:
Asc
Description:
Returns an Integer representing the ASCII character code corresponding to the first letter in a string.
(For an ASCII character reference, click here.)
Syntax:
Asc(string)
Examples:
intCode =
' intCode
intCode =
' intCode
Function Name:
Asc("*")
now has the value 42
Asc("ABC")
now has the value 65
Chr
Description:
Returns a string containing the character associated with the specified ASCII character code.
(For an ASCII character reference, click here.)
Syntax:
Chr(charcode)
Where charcode is a number from 0 to 255 that identifies the character.
Examples:
strChar = Chr(65)
' strChar now contains "A"
"Try It" Example
To demonstrate the built-in string functions, set up a "Try It" console project, and place the following code in the main method:
Sub Main()
Dim strTest As String
Console.Write("Please enter a string: ")
strTest = Console.ReadLine()
Console.WriteLine("Using Len and Length: <" _
& CStr(Len(strTest)) & "><" & CStr(strTest.Length) & ">")
Console.WriteLine("Using Mid, Left, Right, and Substring: <" _
& Mid(strTest, 3, 4) _
& "><" & Microsoft.VisualBasic.Left(strTest, 3) _
& "><" & Microsoft.VisualBasic.Right(strTest, 2) _
& "><" & strTest.Substring(2, 4) & ">")
Console.WriteLine("Using Chars: <" & strTest.Chars(0) & "><" & strTest(7) & ">")
Console.WriteLine("Using StartsWith and EndsWith: <" _
& CStr(strTest.StartsWith(" Vis")) _
& "><" & CStr(strTest.EndsWith("ic")) & ">")
Console.WriteLine("Using Instr, IndexOf, InstrRev, and LastIndexOf: <" _
& CStr(InStr(strTest, "a")) _
& "><" & CStr(strTest.IndexOf("a")) _
& "><" & CStr(InStrRev(strTest, "a")) _
& "><" & CStr(strTest.LastIndexOf("a")) & ">")
Console.WriteLine("Using Contains: <" & CStr(strTest.Contains("asi")) & ">")
Console.WriteLine("Using the Replace function and Replace method: <" _
& Replace(strTest, "a", "*") & "><" & strTest.Replace("a", "*") & ">")
Console.WriteLine("Using UCase and ToUpper: <" _
& UCase(strTest) & "><" & strTest.ToUpper & ">")
Console.WriteLine("Using LCase, and ToLower: <" _
& LCase(strTest) & "><" & strTest.ToLower & ">")
Console.WriteLine("Using LTrim and TrimStart: <" _
& LTrim(strTest) & "><" & strTest.TrimStart & ">")
Console.WriteLine("Using RTrim and TrimEnd: <" _
& RTrim(strTest) & "><" & strTest.TrimEnd & ">")
Console.WriteLine("Using the Trim function and Trim method: <" _
& Trim(strTest) & "><" & strTest.Trim & ">")
Console.WriteLine("Using Concat: <" & String.Concat(strTest, "-", strTest) & ">")
Console.WriteLine("Using Insert: <" & strTest.Insert(3, "*****") & ">")
Console.WriteLine("Using Remove: <" & strTest.Remove(3, 2) & ">")
Console.WriteLine("Using PadLeft and PadRight: <" _
& strTest.PadLeft(20, "*") & "><" & strTest.PadRight(20) & ">")
Console.WriteLine("Using String, Space, and Chr: <" _
& New String("*", 3) & Space(2) & Trim(strTest) & Space(2) _
& New String(Chr(42), 3) & ">")
Console.WriteLine("Using StrReverse: <" & StrReverse(strTest) & ">")
Console.WriteLine("Using Asc: <" & CStr(Asc(strTest)) & ">")
Console.WriteLine("")
Console.WriteLine("(Press Enter to close this window.)")
Console.ReadLine()
End Sub
Run the project and enter a string of your choice.
Some tips on what to enter:
To see the effects of UCase, LCase, ToUpper, and ToLower, enter a mixed case string.
To see the effects of Instr, InstrRev, IndexOf, and LastIndexOf, enter a string with at least two "a"s in it.
To see the effects of LTrim, RTrim, TrimStart, TrimEnd, and Trim, enter a string with leading and/or trailing spaces.
To see the effect of Replace, enter a string with at least one "a" in it.
You can also modify the code and run the project to see if you get the results you expect.
The screen shot below shows a run of the project using the code above where the string Visual Basic was input:
Download the VB project code for the example above here.