Professional Documents
Culture Documents
Bab 1 - 09507131028
Bab 1 - 09507131028
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.
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.
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:
Microsoft.VisualBasic VB.NET
Namespace Function Method
Function / Method
Name: Left
Part Description
string Required. String expression from which the
leftmost characters are returned.
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).
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.)
Part Description
string Required. String expression from which the
rightmost characters are returned.
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).
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:
It is also legal syntax to omit the ".Chars" part. If omitted, the Chars method will be assumed, as in the example below:
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:
is equivalent to:
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:
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.
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.
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.
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:
is equivalent to:
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.
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.
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
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.
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.
Example: strTest = Trim(" Visual Basic ") strTest = " Visual Basic ".Trim
' strTest now contains "Visual Basic" ' strTest now contains "Visual Basic"
Description: Concatenates two or more strings together. This can be used as an alternative to the + or & operators.
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.
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.
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.
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.
Description: Returns a string in which the character order of a specified string is reversed.
Syntax: Space(number)
Where number is the number of blank spaces desired.
Description: Returns an Integer representing the ASCII character code corresponding to the first letter in a string.
Syntax: Asc(string)
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.
To demonstrate the built-in string functions described above, create a new "Try It" project, and place the following code in Sub
Main:
Console.WriteLine("")
Console.WriteLine("(Press Enter to close this window.)")
Console.ReadLine()
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.
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.
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.
Description: Returns a zero-based array containing subset of a string array based on a specified filter criteria.
Syntax: Filter(InputStrings, Value[, Include[, Compare]])
Part Description
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.
astrFruit(0) = "apple"
astrFruit(1) = "peach"
astrFruit(2) = "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
Sub Main()
Console.WriteLine("")
Console.WriteLine("(Press Enter to close this window.)")
Console.ReadLine()
End Sub
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:
causes the comma-delimited string we entered ("Abby,Bubba,Charlie,Debbie,Edgar") to be stored in the variable "strInputString".
The lines:
Console.WriteLine("Split Items:")
astrSplitItems = strInputString.Split(",")
For intX = 0 To UBound(astrSplitItems)
Console.WriteLine("Item(" & CStr(intX) & "): " & astrSplitItems(intX))
Next
Console.WriteLine()
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:
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:
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.