Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

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.

A Few Words about the Microsoft.VisualBasic Namespace

Before we get to the "good stuff" (the string handling functions below), I'd like to say a few words about the Microsoft.VisualBasic
namespace. In addition to "native .NET" methods for handling strings, dates, file input/output and the like, the .NET framework
includes the Microsoft.VisualBasic namespace, which contains functions that will look very familiar to classic VB (pre-.NET)
programmers. In nearly all cases, the MS.VB namespace functions behave identically to their pre-.NET (i.e., VB6) counterparts.
However, whether or not the Microsoft.VisualBasic namespace functions should be used has been the subject of some debate.

"Purists" will argue that only the native .NET methods should be used because they are common across all .NET languages (C# for
example), that the MS.VB namespace functions may not be supported in future versions (although Microsoft insiders have actually
indicated the opposite), and for more subjective reasons (such as a desire to make a clean break with the past, or the attitude that
these "legacy" functions are simply not the ".NET way").

On the other hand, it is no less efficient to use the MS.VB namespace functions (and in many cases they are more efficient), in
some cases they provide functionality not easily replicated with native .NET methods, and from a productivity standpoint, they
provide a comfort zone to those coming to .NET from a VB6 or VBA background. (In my view, using the functionality provided by
the Microsoft.VisualBasic namespace is perfectly fine. It is part of the .NET framework and there are no plans to retire it. I routinely
use these functions as I see fit, as called for by the task at hand.)

Please note that the Microsoft.VisualBasic namespace should not be confused with
the Microsoft.VisualBasic.Compatibility namespace, which is used primarily by upgrade tools and should generally NOT be used
for development.

As stated above, 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 VB.NET
Namespace Function Property
Function / Property
Len Length
Name:
Description: Returns an integer containing the length of the Returns an integer containing the length of the
specified string. specified string.

Syntax: Len(string) String.Length


Where string is the string whose length (number of Where string is the string whose length (number
characters) is to be returned. of characters) is to be returned.

Example: intLen = Len("Visual Basic") intLen = "Visual Basic".Length


' intLen now has the value 12 ' intLen now has the value 12

Getting Parts of a String (Substrings)


Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
Mid Substring
Name:
Description: Returns a substring containing a specified number Returns a substring containing a specified
of characters from a string. number of characters from a string.

Syntax: Mid(string, start[, length]) String.Substring(start, length)

The Mid function syntax has these parts: start Required; Integer. Character position in
string at which the part to be taken
Part Description begins. If start is greater than or equal
string Required. String expression from which to the number of characters in string,
characters are returned. Substring throws an exception.

start Required; Integer. Character position in length Optional; Integer. Number of characters
string at which the part to be taken begins. to return. If omitted all characters from
If start is greater than the number of the start position to the end of the string
characters in string, Mid returns a zero- are returned.
length string ("").
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 = "Visual


' strSubstr now contains "sual" Basic".Substring(2, 4)
' strSubstr now contains "sual"
NOTE: The Mid function is one-based (i.e., the first
position of a string is 1). NOTE: The Substring method is zero-based (i.e.,
the first position of a string is 0).
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"


Mid(strTest, 3, 4) = "xxxx"
' strTest now contains "Vixxxx Basic"

Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
Name: Left

(NOTE: If used in a Forms code module, the Left


function must be qualified with "Strings." because (use Substring)
Left is also a property in
the Windows.Forms.Formnamespace. Otherwise,
the "Strings".qualifier is optional.)

Description: Returns a substring containing a specified number


of characters from the beginning (left side) of a
string.

Syntax: Left(string, length)

The Left function syntax has these parts:

Part Description
string 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 = Strings.Left ("Visual strSubstr = "Visual


Basic", 3) Basic".Substring(0, 3)
' strSubstr now contains "Vis" ' strSubstr now contains "Vis"

NOTE: The Left function is one-based (i.e., the first REMINDER: The Substring method is zero-
position of a string is 1). 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 VB.NET
Namespace Function Method
Function / Method
(use Substring)
Name: Right
(NOTE: If used in a Forms code module, the Right
function must be qualified with "Strings." because
Right is also a property in
theWindows.Forms.Form namespace. Otherwise,
the "Strings".qualifier is optional.)

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 Description
string 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 string is
returned.

Example: strSubstr = Strings.Right("Visual strSubstr = "Visual


Basic", 3) Basic".Substring(9, 3)
' strSubstr now contains "sic" ' strSubstr now contains "sic"

NOTE: The Right function is one-based (i.e., the first REMINDER: The Substring method is zero-
position of a string is 1). 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 Strings.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 Strings.Right(strTest, 2) = "ic" Then ...

Finding One String Within Another


Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
Instr IndexOf
Name:
Description: Returns an integer specifying the position of Returns an integer specifying the position of one string
one string within another. The search starts within another. The search starts either at the first
either at the first character position or at the character position or at the position specified by
position specified by the start argument, and thestartindex argument, and proceeds forward toward
proceeds forward toward the end of the string the end of the string (stopping when either string is
(stopping when either string2 is found or when found or when the end of the string being searched is
the end of the string1 is reached). If the string reached). If the string is not found, -1 is returned.
is not found, 0 is returned. IndexOf performs a case-sensitive search.

Syntax: InStr String.IndexOf(string [, startindex])


([start,] string1, string2 [,
compare]) string String expression sought.

The InStr function syntax has these parts: startindex Optional. Numeric expression that sets the
starting position for each search. If
Part Description omitted, search begins at
the first character position.
start Optional. Numeric expression that
sets the starting position for each
search. If omitted, search begins
at the firstcharacter 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
(case-sensitive) search. A value
of 1 specifies a textual (case-
insensitive) 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"
constantsvbBinaryCompare and vbTextCom
pare 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", intPos = "Visual Basic".IndexOf("a")


"a") ' intPos now has the value 4
' intPos now has the value 5
' (search started at position 1 intPos = "Visual Basic".IndexOf("a", 6)
' by default and is case-sensitive ' intPos now has the value 8
' by default)
intPos = "Visual Basic".IndexOf("A")
intPos = Instr(6, "Visual Basic", ' intPos now has the value -1
"a")
' intPos now has the value 9 NOTE: The IndexOf method is zero-based (i.e., the first
' (search started at position 6 position of a string is 0).
' and is case-sensitive by
default)

intPos = Instr("Visual Basic",


"A")
' intPos now has the value 0
' (case-sensitive search was
performed
' by default)

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).

Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
InstrRev LastIndexOf
Name:
Description: Returns an integer specifying the position of Returns an integer specifying the position of one string
one string within another. The search starts within another. The search starts either at the last
either at the last character position or at the character position or at the position specified by
position specified by the start argument, and thestartindex argument, and proceeds backward toward
proceeds backward toward the beginning of the beginning of the string (stopping when either stringis
the string (stopping when eitherstring2 is found found or when the beginning of the string being
or when the beginning of the string1is searched is reached). If the string is not found, -1 is
reached). If the string is not found, 0 is returned. LastIndexOf performs a case-sensitive
returned. search.

Syntax: InStrRev String.LastIndexOf(string [, startindex])


(string1, string2[, start, [,
compare]]) string String expression sought.

The InStrRev function syntax has these parts: startindex Optional. Numeric expression that sets the
starting position for each search. If
Part Description omitted, search begins at
the last character position.
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 lastcharacter position.

compare Optional; numeric. A value of 0


(the default) specifies a binary
(case-sensitive) search. A value
of 1 specifies a textual (case-
insensitive) 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"
constantsvbBinaryCompare and vbTextCom
pare can be used for 0 and 1 respectively.
Example: intPos = InstrRev("Visual Basic", intPos = "Visual Basic".LastIndexOf("a")
"a") ' intPos now has the value 8
' intPos now has the value 9
' (search started at last position intPos = _
' by default and is case-sensitive "Visual Basic".LastIndexOf("a", 6)
' by default) ' intPos now has the value 4

intPos = InstrRev("Visual Basic", intPos = "Visual Basic".LastIndexOf("A")


_ ' intPos now has the value -1
"a", 6)
' intPos now has the value 5 NOTE: The LastIndexOf method is zero-based (i.e., the
' (search started at position 6 first position of a string is 0).
' 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).

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 VB.NET
Namespace Function Method
Function /
Replace Replace
Method Name:
Description: Returns a string in which a specified substring has Returns a string in which all occurrences of a specified
been replaced with another substring a specified substring has been replaced with another substring.
number of times.

Syntax: Replace String.Replace(oldstring, newstring)


(expression, find, replacewith[,start
[, count[, compare]]]) oldstring Required. Substring being searched
for.
The Replace function syntax has these parts:
newstring Required. Replacement substring.
Part Description

expression Required. String expression


containing substring to replace.

find Required. Substring being


searched for.
replacewith Required. Replacement substring.

start Optional. Position


within expressionwhere
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 = case-
insensitive)

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"
constantsvbBinaryCompare and vbTextCompar
e can be used for 0 and 1 respectively.

Example: strNewDate = _ strNewDate = _


Replace("08/31/2001", "/", "-") "08/31/2001".Replace("/", "-")
' strNewDate now contains "08-31- ' strNewDate now contains "08-31-2001"
2001"

Casing Strings
Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
UCase ToUpper
Name:
Description: Converts all lowercase letters in a string to Converts all lowercase letters in a string to
uppercase. Any existing uppercase letters and uppercase. Any existing uppercase letters and non-
non-alpha characters remain unchanged. alpha characters remain unchanged.

Syntax: UCase(string) String.ToUpper

Example: strNew = UCase("Visual Basic") strNew = "Visual Basic".ToUpper


' strNew now contains "VISUAL ' strNew now contains "VISUAL BASIC"
BASIC"

Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
LCase ToLower
Name:
Description: Converts all uppercase letters in a string to Converts all uppercase letters in a string to
lowercase. Any existing lowercase letters and lowercase. Any existing lowercase letters and non-
non-alpha characters remain unchanged. alpha characters remain unchanged.

Syntax: LCase(string) String.ToLower

Example: strNew = LCase("Visual Basic") strNew = "Visual Basic".ToLower


' strNew now contains "visual ' strNew now contains "visual basic"
basic"

Trimming Strings
Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
LTrim TrimStart
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 = " Visual


' strTest now contains "Visual Basic ".TrimStart
Basic " ' strTest now contains "Visual
Basic "

Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
RTrim TrimEnd
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 = " Visual Basic ".TrimEnd
' strTest now contains " Visual ' strTest now contains " Visual
Basic" Basic"

Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
Trim Trim
Name:
Description: Removes both leading and trailing blank spaces Removes both leading and trailing blank spaces
from a string. from a string.

Syntax: Trim(string) String.Trim

Example: strTest = Trim(" Visual Basic ") strTest = " Visual Basic ".Trim
' strTest now contains "Visual Basic" ' 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)

startindex Required. The (zero-based) position at which to insert characters.

value Required. The string of characters to insert.

Example: 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])

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.

Examples: strTest = "Two hundred dollars."


strTest = strTest.Remove(4, 8)
' strTest now contains "Two dollars."

strTest = strTest.Remove(3)
' strTest now contains "Two"

Padding Strings
Method Name: PadLeft
Description: 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: PadRight


Description: 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 Optional. The character to pad the string with. If omitted, a blank space will be used.

Example: 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 The number of characters to pad the string with.

Examples: 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.

Syntax: Asc(string)

Examples: intCode = Asc("*")


' intCode now has the value 42
intCode = Asc("ABC")
' intCode now has the value 65

Function Name: Chr

Description: Returns a string containing the character associated with the specified ASCII character code.

Syntax: Chr(charcode)
Where charcode is a number from 0 to 255 that identifies the character.

Examples: strChar = Chr(65)


' strChar now contains "A"

To demonstrate the built-in string functions described above, create a new "Try It" project, and place the following code in 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) _
& "><" & Strings.Left(strTest, 3) _
& "><" & Strings.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()

Run the project and enter a string of


your choice.

Some tips on what to enter:


To see the effects
of UCase, LCase, ToUppe
r, and ToLower, enter a
mixed case string.
To see the effects
of Instr, InstrRev, IndexOf
, andLastIndexOf, enter a
string with at least two "a"s
in it.
To see the effects
of LTrim, RTrim, TrimStar
t, TrimEnd, andTrim, 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 on the right shows


a run of the project using the code
above where the string Visual
Basic was input:

String Array Functions


(Split, Join, and Filter)

Split, Join, and Filter form a trio of powerful functions that operate on string arrays. These functions save the coding effort of having
to set up loops and using combinations of other basic string functions to perform the equivalent tasks. These functions are
summarized as follows:

Split Splits a string into separate elements based on a delimiter (such as a comma or space) and stores the
resulting elements in a zero-based array. Split is available both as a Microsoft.VisualBasic namespace
function as well as a native .NET method.

Join Joins (concatenates) elements of an array into an output string. Join is available both as a
Microsoft.VisualBasic namespace function as well as a native .NET method.

Filter Returns a zero-based array containing subset of a string array based on a specified filter criteria. This
function is the least commonly used of the three, but can be useful in some circumstances. Filter is
available only as a Microsoft.VisualBasic namespace function; there is no equivalent native .NET method.

The Split, Join, and Filter functions are described in further detail below:

Microsoft.VisualBasic VB.NET
Namespace Function Method
Function /
Method Split Split
Name:
Description: Splits a string into separate elements (substrings) based Splits a string into separate elements (substrings)
on a delimiter (such as a comma or space) and stores the based on a delimiter (such as a comma or space)
resulting elements (substrings) in a zero-based, one- and stores the resulting elements (substrings) in a
dimensional array. zero-based, one-dimensional array.
Syntax: Split String.Split([delimiter[,count]])
(expression,[,delimiter[,count[,compare]]])
delimiter Optional. String character used to
The Split function syntax has these parts: identify substring limits. If omitted, the
space character (" ") is assumed to be
Part Description the delimiter. If delimiter is a zero-
length string, a single-element array
expression Required. String expression containing containing the entire expression string
substrings and delimiters. If expression is returned.
is a zero-length string(""), Split returns
an empty array, that is, an array with no count Optional. Maximum number of
elements and no data. substrings to be returned; by default,
all substrings are returned.
delimiter Optional. String character used to identify
substring limits. If omitted, the space
character (" ") is assumed to be the
delimiter. If delimiter is a zero-length
string, a single-element array containing
the entire expression string is returned.

count Optional. Maximum number of substrings


to be returned; by default, all substrings
are returned.

compare Optional. Numeric value indicating the


kind of comparison to use when
evaluating substrings (0 = case
sensitive, 1 = case-insensitive).

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: Dim astrNameParts() As String Dim astrNameParts() As String


Dim strNameData As String = "John,J.,Doe" Dim strNameData As String _
astrNameParts = Split(strNameData, ",") = "John,J.,Doe"
' astrNameParts now contains 3 elements: astrNameParts =
' astrNameParts(0) contains "John" strNameData.Split(",")
' astrNameParts(1) contains "J." ' astrNameParts now contains 3
' astrNameParts(2) contains "Doe" elements:
' astrNameParts(0) contains "John"
' astrNameParts(1) contains "J."
' astrNameParts(2) contains "Doe"

Microsoft.VisualBasic VB.NET
Namespace Function Method
Function /
Method Join Join
Name:
Description: Returns a string created by joining a number of Returns a string created by joining a number of
substrings contained in an array. substrings contained in an array.

Syntax: Join(list[,delimiter]) String.Join(delimiter,list)

The Join function syntax has these parts: delimiter String character used to separate the
substrings in the returned string.
Part Description
list One-dimensional array containing
list Required. One-dimensional array substrings to be joined.
containing substrings to be joined.

delimiter Optional. String character used to


separate the substrings in the
returned string. If omitted, the space
character (" ") is used. If delimiter is
a zero-length string (""), all items in
the list are concatenated with no
delimiters.

Example: Dim astrFruit() As String Dim astrFruit() As String


ReDim astrFruit(2) ReDim astrFruit(2)
astrFruit(0) = "apple" astrFruit(0) = "apple"
astrFruit(1) = "peach" astrFruit(1) = "peach"
astrFruit(2) = "pear" astrFruit(2) = "pear"
Dim strAllFruit As String Dim strAllFruit As String
strAllFruit = Join(astrFruit, "|") strAllFruit = String.Join("|",
' strAllFruit now contains astrFruit)
"apple|peach|pear" ' strAllFruit now contains
"apple|peach|pear"

Function Name: Filter

Description: Returns a zero-based array containing subset of a string array based on a specified filter criteria.
Syntax: Filter(InputStrings, Value[, Include[, Compare]])

The Filter function syntax has these parts:

Part Description

InputStrings Required. One-dimensional array of strings to be searched.

Value Required. String to search for.

Include Optional. Boolean value indicating whether to return substrings that include or
exclude Value. IfInclude is True, Filter returns the subset of the array that
contains Value as a substring. IfInclude is False, Filter returns the subset of the array
that does not contain Value as a substring.

Compare Optional. Numeric value indicating the kind of comparison to use (0 = case sensitive, 1 =
case-insensitive).

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: Dim astrFruit() As String


ReDim astrFruit(2)
Dim astrNewFruit() As String

astrFruit(0) = "apple"
astrFruit(1) = "peach"
astrFruit(2) = "pear"

astrNewFruit = Filter(astrFruit, "PEA", True, CompareMethod.Text)

' astrNewFruit now has two elements:


' astrNewFruit(0) = "peach"
' astrNewFruit(1) = "pear"

A "Try It" example has been set up to demonstrate how these three functions might be used.

Suppose you were given an input string of comma-delimited names, such as:

Abby,Bubba,Charlie,Debbie,Edgar

and you wanted to "weed out" only the names that contained a double "b" ("bb") and output the results as a similar comma-
delimited string:

Abby,Bubba,Debbie

The "Try It" code to accomplish this is shown below:

Sub Main()

Dim strInputString As String


Dim strFilterText As String
Dim astrSplitItems() As String
Dim astrFilteredItems() As String
Dim strFilteredString As String
Dim intX As Integer

Console.Write("Enter a comma-delimited string of items: ")


strInputString = Console.ReadLine()
Console.Write("Enter Filter: ")
strFilterText = Console.ReadLine()

Console.WriteLine("Original Input String: " & strInputString)


Console.WriteLine()
Console.WriteLine("Split Items:")
astrSplitItems = strInputString.Split(",")
For intX = 0 To UBound(astrSplitItems)
Console.WriteLine("Item(" & CStr(intX) & "): " & astrSplitItems(intX))
Next
Console.WriteLine()
Console.WriteLine("Filtered Items (using '" & strFilterText & "'):")
astrFilteredItems = Filter(astrSplitItems, strFilterText, True, CompareMethod.Text)
For intX = 0 To UBound(astrFilteredItems)
Console.WriteLine("Item(" & CStr(intX) & "): " & astrFilteredItems(intX))
Next
Console.WriteLine()
strFilteredString = String.Join(",", astrFilteredItems)
Console.WriteLine("Filtered Output String: " & strFilteredString)

Console.WriteLine("")
Console.WriteLine("(Press Enter to close this window.)")
Console.ReadLine()

End Sub

Screen shot of run:

Let us analyze the "Try It" code to explain how this works.

First, the necessary variables are declared. Note that the presence of an empty pair of parentheses following "astrSplitItems" and
"astrFilteredItems" declares these items as dynamic arrays:

Dim strInputString As String


Dim strFilterText As String
Dim astrSplitItems() As String
Dim astrFilteredItems() As String
Dim strFilteredString As String
Dim intX As Integer
Next, we prompt for our input data. The line

Console.Write("Enter a comma-delimited string of items: ")


strInputString = Console.ReadLine()

causes the comma-delimited string we entered ("Abby,Bubba,Charlie,Debbie,Edgar") to be stored in the variable "strInputString".

The lines:

Console.Write("Enter Filter: ")


strFilterText = Console.ReadLine()

caused the "bb" filter we entered to be stored in the variable "strFilterText".

Next, we simply print out the string that was input:

Console.WriteLine("Original Input String: " & strInputString)


Console.WriteLine()

Then it gets interesting in the next segment:

Console.WriteLine("Split Items:")
astrSplitItems = strInputString.Split(",")
For intX = 0 To UBound(astrSplitItems)
Console.WriteLine("Item(" & CStr(intX) & "): " & astrSplitItems(intX))
Next
Console.WriteLine()

In the segment above, the line

astrSplitItems = strInputString.Split(",")

causes the five names we entered ("Abby,Bubba,Charlie,Debbie,Edgar") to be stored in separate elements of the "astrSplitItems"
dynamic array, indexed from 0 to 4 (i.e., astrSplitItems(0) will contain "Abby" while astrSplitItems(4) will contain "Edgar").

The For/Next loop in the segment displays the array contents so we can verify the results of the Split function:

For intX = 0 To UBound(astrSplitItems)


Console.WriteLine("Item(" & CStr(intX) & "): " & astrSplitItems(intX))
Next

The filtering occurs in the next segment:

Console.WriteLine("Filtered Items (using '" & strFilterText & "'):")


astrFilteredItems = Filter(astrSplitItems, strFilterText, True, CompareMethod.Text)
For intX = 0 To UBound(astrFilteredItems)
Console.WriteLine("Item(" & CStr(intX) & "): " & astrFilteredItems(intX))
Next
Console.WriteLine()

In the segment above, the line

astrFilteredItems = Filter(astrSplitItems, strFilterText, True, CompareMethod.Text)

tells the Filter function to take the array of five names (astrSplitItems), go thru and apply the filter criteria to it (the "bb" that is
contained in the strFilterText variable), and place the results of the filtering in the "astrFilteredItems" dynamic array. In this
particular case, three names matched the filter (Abby, Bubba, and Debbie), so those three names were stored in indexes 0 to 2 of
the astrFilteredItems array.

The For/Next loop in the segment displays the filtered array contents so we can verify the results of the Filter function:

For intX = 0 To UBound(astrFilteredItems)


Console.WriteLine("Item(" & CStr(intX) & "): " & astrFilteredItems(intX))
Next

In the last lines of the "Try It" code, the line

strFilteredString = String.Join(",", astrFilteredItems)

uses the Join method to create one string that is the result of concatenating all elements of the astrFilteredItems array, separating
each item with a comma.
The line
Console.WriteLine("Filtered Output String: " & strFilteredString)
shows the resulting "joined" string.

You might also like