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 Namespace Function |
VB.NET Property |
Function / Property Name: |
Len |
Length |
Description: |
Returns an integer containing the length of the specified string. |
Returns an integer containing the length of the specified string.
|
Syntax: |
Len(string) Where string is the string whose length (number of characters) is to be returned. |
String.Length Where string is the string whose length (number of characters) is to be returned.
|
Example: |
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 |
VB.NET Method |
Function / Method Name: |
Mid |
Substring |
Description: |
Returns a substring containing a specified number of characters from a string.
|
Returns a substring containing a specified number of characters from a string.
|
Syntax: |
Mid(string, start[, length])
The Mid function syntax has these parts:
Part Description string 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 ("").
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.
|
String.Substring(start, length)
start 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.
|
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" Mid(strTest, 3, 4) = "xxxx" ' strTest now contains "Vixxxx 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). |
|
Microsoft.VisualBasic Namespace Function |
VB.NET Method |
Function / Method Name: |
Left
(NOTE: If used in a Forms code module, the Left function must be qualified with "Strings." because Left is also a property in the Windows.Forms.Form namespace. Otherwise, the "Strings".qualifier is optional.)
|
(use Substring) |
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 Basic", 3) ' strSubstr now contains "Vis"
NOTE: The Left function is one-based (i.e., the first position of a string is 1).
' Note that the same thing could be ' accomplished with Mid: strSubstr = Mid("Visual Basic", 1, 3)
|
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). |
|
Microsoft.VisualBasic Namespace Function |
VB.NET Method |
Function / Method 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 the Windows.Forms.Form namespace. Otherwise, the "Strings".qualifier is optional.)
|
(use Substring) |
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 Basic", 3) ' strSubstr now contains "sic"
NOTE: The Right function is one-based (i.e., the first position of a string is 1).
' Note that the same thing could be ' accomplished with Mid: strSubstr = Mid("Visual Basic", 10, 3)
|
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). |
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 Namespace Function |
VB.NET Method |
Function / Method Name: |
Instr |
IndexOf |
Description: |
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])
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 (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" 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.
|
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.
|
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 = Instr(6, "Visual Basic", "a") ' intPos now has the value 9 ' (search started at position 6 ' 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).
|
intPos = "Visual Basic".IndexOf("a") ' intPos now has the value 4
intPos = "Visual Basic".IndexOf("a", 6) ' intPos now has the value 8
intPos = "Visual Basic".IndexOf("A") ' intPos now has the value -1
NOTE: The IndexOf method is zero-based (i.e., the first position of a string is 0).
|
|
Microsoft.VisualBasic Namespace Function |
VB.NET Method |
Function / Method Name: |
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]])
The InStrRev function syntax has these parts:
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 (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" constants vbBinaryCompare and vbTextCompare can be used for 0 and 1 respectively.
|
String.LastIndexOf(string [, startindex])
string String expression sought.
startindex Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the last character position.
|
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 |
VB.NET Method |
Function / Method Name: |
Replace |
Replace |
Description: |
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.
|
Syntax: |
Replace (expression, find, replacewith[, start[, count[, compare]]])
The Replace function syntax has these parts:
Part Description
expression Required. String expression containing substring to replace.
find 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 = 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.
|
String.Replace(oldstring, newstring)
oldstring Required. Substring being searched for.
newstring Required. Replacement substring.
|
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 |
VB.NET Method |
Function / Method Name: |
UCase |
ToUpper |
Description: |
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"
|
|
Microsoft.VisualBasic Namespace Function |
VB.NET Method |
Function / Method Name: |
LCase |
ToLower |
Description: |
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 non-alpha 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: |
LTrim |
TrimStart |
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 "
|
strTest = " Visual Basic ".TrimStart ' strTest now contains "Visual Basic "
|
|
Microsoft.VisualBasic Namespace Function |
VB.NET Method |
Function / Method Name: |
RTrim |
TrimEnd |
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"
|
|
Microsoft.VisualBasic Namespace Function |
VB.NET Method |
Function / Method Name: |
Trim |
Trim |
Description: |
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)
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. (For an ASCII character reference, click here.)
|
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. (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"
|
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:
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:
|
Download the VB.NET project code for the example above here.
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 Namespace Function |
VB.NET Method |
Function / Method Name: |
Split |
Split |
Description: |
Splits a string into separate elements (substrings) based on a delimiter (such as a comma or space) and stores the resulting elements (substrings) in a zero-based, one-dimensional array. |
Splits a string into separate elements (substrings) based on a delimiter (such as a comma or space) and stores the resulting elements (substrings) in a zero-based, one-dimensional array. |
Syntax: |
Split (expression,[,delimiter[,count[,compare]]])
The Split function syntax has these parts:
Part Description
expression Required. String expression containing substrings and delimiters. If expression is a zero-length string(""), Split returns an empty array, that is, an array with no elements and no data.
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.
|
String.Split([delimiter[,count]])
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.
|
Example: |
Dim astrNameParts() As String Dim strNameData As String = "John,J.,Doe" astrNameParts = Split(strNameData, ",") ' astrNameParts now contains 3 elements: ' astrNameParts(0) contains "John" ' astrNameParts(1) contains "J." ' astrNameParts(2) contains "Doe"
|
Dim astrNameParts() As String Dim strNameData As String _ = "John,J.,Doe" astrNameParts = strNameData.Split(",") ' astrNameParts now contains 3 elements: ' astrNameParts(0) contains "John" ' astrNameParts(1) contains "J." ' astrNameParts(2) contains "Doe"
|
|
Microsoft.VisualBasic Namespace Function |
VB.NET Method |
Function / Method Name: |
Join |
Join |
Description: |
Returns a string created by joining a number of substrings contained in an array. |
Returns a string created by joining a number of substrings contained in an array.
|
Syntax: |
Join(list[,delimiter])
The Join function syntax has these parts:
Part Description
list Required. One-dimensional array 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.
|
String.Join(delimiter,list)
delimiter String character used to separate the substrings in the returned string.
list One-dimensional array containing substrings to be joined.
|
Example: |
Dim astrFruit() As String ReDim astrFruit(2) astrFruit(0) = "apple" astrFruit(1) = "peach" astrFruit(2) = "pear" Dim strAllFruit As String strAllFruit = Join(astrFruit, "|") ' strAllFruit now contains "apple|peach|pear"
|
Dim astrFruit() As String ReDim astrFruit(2) astrFruit(0) = "apple" astrFruit(1) = "peach" astrFruit(2) = "pear" Dim strAllFruit As String strAllFruit = String.Join("|", astrFruit) ' 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. If Include is True, Filter returns the subset of the array that contains Value as a substring. If Include 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.
Download the VB project code for the example above here.