Friday, March 2, 2012

VB.NET Strings

VB.NET has amazing support for handling strings. This includes both the native .NET methods as well as the ones in Microsoft provided Microsoft.VisualBasic namespace (which makes migrating from VB6 over to VB.NET much easier). This tutorial goes through most of the string handling functions in in both these areas and compares them to each other.

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.

Microsoft.VisualBasic Namespace Function

Returns an integer containing the length of the specified string.

Returns an integer containing the length of the specified string.

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.

intLen = Len("Visual Basic") ' intLen now has the value 12intLen = "Visual Basic".Length' intLen now has the value 12Getting Parts of a String (Substrings)

Microsoft.VisualBasic Namespace Function

Returns a substring containing a specified number of characters from a string.

Returns a substring containing a specified number of characters from a string.

Mid(string, start[, length])

The Mid function syntax has these parts:

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.

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

Left

(NOTE: The Left function must be qualified with the Microsoft.VisualBasic namespace because Left is also a property in the Windows.Forms.Form namespace.)

Returns a substring containing a specified number of characters from the beginning (left side) of a string.

Left(string, length)

The Left function syntax has these parts:

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.

strSubstr = _ Microsoft.VisualBasic.Left _ ("Visual Basic", 3)' strSubstr now contains "Vis"

NOTE: The Left function is one-based (i.e., the first position of a string is 1).

' Note that the same thing could be' accomplished with MidstrSubstr = 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

Right

(NOTE: The Right function must be qualified with the Microsoft.VisualBasic namespace because Right is also a property in the Windows.Forms.Form namespace.)

Returns a substring containing a specified number of characters from the end (right side) of a string.

Right(string, length)

The Right function syntax has these parts:

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.

strSubstr = _ Microsoft.VisualBasic.Right _ ("Visual Basic", 3)' strSubstr now contains "sic"

NOTE: The Right function is one-based (i.e., the first position of a string is 1).

' 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 CharDim 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 CharDim strTest As String = "Visual Basic"chrTheChar = strTest(2)' chrTheChar now contains "s"

If you want to test whether or not a string begins with a certain combination of characters, you can use the StartsWith method, which returns a Boolean True or False value indicating whether or not the string being tested starts with the characters given as the argument. Therefore:

       If strTest.StartsWith("Vis") Then ...

is equivalent to:

       If strTest.Substring(0, 3) = "Vis" Then ...

or:

       If Microsoft.VisualBasic.Left(strTest, 3) = "Vis" Then ...

If you want to test whether or not a string ends with a certain combination of characters, you can use the EndsWith method, which returns a Boolean True or False value indicating whether or not the string being tested ends with the characters given as the argument. Therefore:

       If strTest.EndsWith("ic") Then ...

is equivalent to:

       If strTest.Substring(10, 2) = "ic" Then ...

or:

       If Microsoft.VisualBasic.Right(strTest, 2) = "ic" Then ... Finding One String Within Another

Microsoft.VisualBasic Namespace Function

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 thestring being searchedis reached). If the string is not found, -1 is returned. IndexOf performs a case-sensitive search.

InStr

([start,] string1, string2 [, compare])

The InStr function syntax has these parts:

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.

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

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.

InStrRev

(string1, string2[, start, [, compare]])

The InStrRev function syntax has these parts:

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.

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

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

Returns a string in which a specified substring has been replaced with another substring a specified number of times.

Returns a string in which all occurrences of a specified substring has been replaced with another substring.

Replace (expression, find, replacewith[, start[, count[, compare]]])

The Replace function syntax has these parts:

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.

strNewDate = _ Replace("08/31/2001", "/", "-")' strNewDate now contains "08-31-2001"strNewDate = _ "08/31/2001".Replace("/", "-")' strNewDate now contains "08-31-2001"Microsoft.VisualBasic Namespace Function

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.

strNew = UCase("Visual Basic")' strNew now contains "VISUAL BASIC"strNew = "Visual Basic".ToUpper' strNew now contains "VISUAL BASIC"Microsoft.VisualBasic Namespace Function

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.

strNew = LCase("Visual Basic")' strNew now contains "visual basic"strNew = "Visual Basic".ToLower' strNew now contains "visual basic"Microsoft.VisualBasic Namespace Function

Removes leading blank spaces from a string.

Removes leading blank spaces from a string.

strTest = LTrim(" Visual Basic ")' strTest now contains "Visual Basic "strTest = " Visual Basic ".TrimStart' strTest now contains "Visual Basic "Microsoft.VisualBasic Namespace Function

Removes trailing blank spaces from a string.

Removes trailing blank spaces from a string.

strTest = RTrim(" Visual Basic ")' strTest now contains " Visual Basic"strTest = " Visual Basic ".TrimEnd' strTest now contains " Visual Basic"Microsoft.VisualBasic

Namespace Function

Removes both leading and trailing blank spaces from a string.

Removes both leading and trailing blank spaces from a string.

strTest = Trim(" Visual Basic ")' strTest now contains "Visual Basic"strTest = " Visual Basic ".Trim' strTest now contains "Visual Basic"More VB.NET String-Handling Methods

Concatenates two or more strings together. This can be used as an alternative to the + or & operators.

String.Concat(string1, string2, ... stringn)

The following three statements are all equivalent:

strTest = String.Concat("Hello ", "World")strTest = "Hello " & "World"strTest = "Hello " + "World"

Inserts characters into a string

String .Insert(startindex, value)

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

value               
Required. The string of characters to insert.

strTest = "The time now."strTest = strTest.Insert(9, "is ")' strTest now contains "The time is now."

Removes characters from a string

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.

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

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.

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.

strName = "John Doe"strNewName = strName.PadLeft(15)' strNewName now contains " John Doe" strNewName = strName.PadLeft(15, "*")' strNewName now contains "*******John Doe"

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.

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.

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)

Can be used to return a string containing a repeating character string of the length specified.

New String(character, count)

character
The character to be repeated.

count              
The number of characters to pad the string with.

strTest = New String("*", 5)' strTest now contains "*****"More Microsoft.VisualBasic Namespace String-Handling Functions

Returns a string in which the character order of a specified string is reversed.

strTest = StrReverse ("Visual Basic") ' strTest now contains "cisaB lausiV"

Returns a string containing the specified number of blank spaces.

Space(number)

Where number is the number of blank spaces desired.

strTest = Space(5)' strTest now contains " "

Returns an Integer representing the ASCII character code corresponding to the first letter in a string.

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

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

Chr(charcode)

Where charcode is a number from 0 to 255 that identifies the character.

strChar = Chr(65)' strChar now contains "A""Try It" Example

To demonstrate the built-in string functions, set up a "Try It" console project, and place the following code in the main method:

Sub Main()Dim strTest AsStringConsole.Write("Please enter a string: ")strTest = Console.ReadLine()Console.WriteLine("Using Len and Length: <" _ & CStr(Len(strTest)) & "><" & CStr(strTest.Length) & ">")Console.WriteLine("Using Mid, Left, Right, and Substring: <" _ & Mid(strTest, 3, 4) _ & "><" & Microsoft.VisualBasic.Left(strTest, 3) _ & "><" & Microsoft.VisualBasic.Right(strTest, 2) _ & "><" & strTest.Substring(2, 4) & ">")Console.WriteLine("Using Chars: <" & strTest.Chars(0) & "><" & strTest(7) & ">")Console.WriteLine("Using StartsWith and EndsWith: <" _ & CStr(strTest.StartsWith(" Vis")) _ & "><" & CStr(strTest.EndsWith("ic")) & ">")Console.WriteLine("Using Instr, IndexOf, InstrRev, and LastIndexOf: <" _ & CStr(InStr(strTest, "a")) _ & "><" & CStr(strTest.IndexOf("a")) _ & "><" & CStr(InStrRev(strTest, "a")) _ & "><" & CStr(strTest.LastIndexOf("a")) & ">")Console.WriteLine("Using Contains: <" & CStr(strTest.Contains("asi")) & ">")Console.WriteLine("Using the Replace function and Replace method: <" _ & Replace(strTest, "a", "*") & "><" & strTest.Replace("a", "*") & ">")Console.WriteLine("Using UCase and ToUpper: <" _ & UCase(strTest) & "><" & strTest.ToUpper & ">")Console.WriteLine("Using LCase, and ToLower: <" _ & LCase(strTest) & "><" & strTest.ToLower & ">")Console.WriteLine("Using LTrim and TrimStart: <" _ & LTrim(strTest) & "><" & strTest.TrimStart & ">")Console.WriteLine("Using RTrim and TrimEnd: <" _ & RTrim(strTest) & "><" & strTest.TrimEnd & ">")Console.WriteLine("Using the Trim function and Trim method: <" _ & Trim(strTest) & "><" & strTest.Trim & ">")Console.WriteLine("Using Concat: <" & String.Concat(strTest, "-", strTest) & ">")Console.WriteLine("Using Insert: <" & strTest.Insert(3, "*****") & ">")Console.WriteLine("Using Remove: <" & strTest.Remove(3, 2) & ">")Console.WriteLine("Using PadLeft and PadRight: <" _ & strTest.PadLeft(20, "*") & "><" & strTest.PadRight(20) & ">")Console.WriteLine("Using String, Space, and Chr: <" _ & NewString("*", 3) & Space(2) & Trim(strTest) & Space(2) _ & NewString(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()EndSub

Run the project and enter a string of your choice.

Some tips on what to enter:

To see the effects of UCase, LCase, ToUpper, and ToLower, enter a mixed case string. To see the effects of Instr, InstrRev, IndexOf, and LastIndexOf, enter a string with at least two "a"s in it. To see the effects of LTrim, RTrim, TrimStart, TrimEnd, and Trim, enter a string with leading and/or trailing spaces. To see the effect of Replace, enter a string with at least one "a" in it.

You can also modify the code and run the project to see if you get the results you expect.

The screen shot below shows a run of the project using the code above where the string Visual Basic was input:

image

Download the VB Project code for this example: VB.NET String Function Example

This article was original written by The VB Programmer.


View the original article here

No comments:

Post a Comment