The
String class of the .NET framework provides many built-in
methods to facilitate the comparison and manipulation of strings. It is
now a trivial matter to get data about a string, or to create new
strings by manipulating current strings. The Visual Basic .NET language
also has inherent methods that duplicate many of these functionalities.
Types of String Manipulation Methods
In
this section you will read about several different ways to analyze and
manipulate your strings. Some of the methods are a part of the Visual
Basic language, and others are inherent in the
String class.
Visual
Basic .NET methods are used as inherent functions of the language. They
may be used without qualification in your code. The following example
shows typical use of a Visual Basic .NET string-manipulation command:
Dim aString As String = "SomeString"
Dim bString As String
bString = Mid(aString, 3, 3)
In this example, the
Mid function performs a direct operation on
aString
and assigns the value to
bString
.
You can also manipulate strings with the methods of the
String class. There are two types of methods in
String:
shared methods and
instance methods.
A shared method is a method that stems from the
String
class itself and does not require an instance of that class to work.
These methods can be qualified with the name of the class (
String) rather than with an instance of the
String class. For example:
Dim aString As String
bString = String.Copy("A literal string")
In the preceding example, the
String.Copy method is a static method, which acts upon an expression it is given and assigns the resulting value to
bString
.
Instance methods, by contrast, stem from a particular instance of
String and must be qualified with the instance name. For example:
Dim aString As String = "A String"
Dim bString As String
bString = aString.SubString(2,6) ' bString = "String"
In this example, the
SubString method is a method of the instance of
String (that is,
aString
). It performs an operation on
aString
and assigns that value to
bString
.
Nothing and Strings
The Visual Basic runtime and the .NET Framework evaluate
Nothing differently when it comes to strings. Consider the following example:
Dim MyString As String = "This is my string"
Dim stringLength As Integer
' Explicitly set the string to Nothing.
MyString = Nothing
' stringLength = 0
stringLength = Len(MyString)
' This line, however, causes an exception to be thrown.
stringLength = MyString.Length
The Visual Basic .NET runtime evaluates
Nothing as an empty
string; that is, "". The .NET Framework, however, does not, and will
throw an exception whenever an attempt is made to perform a string
operation on
Nothing.
Comparing Strings
You can compare two strings by using the
String.Compare
method. This is a static, overloaded method of the base string class.
In its most common form, this method can be used to directly compare two
strings based on their alphabetical sort order. This is similar to the
Visual Basic
StrComp Function function. The following example illustrates how this method is used:
Dim myString As String = "Alphabetical"
Dim secondString As String = "Order"
Dim result As Integer
result = String.Compare (myString, secondString)
This method returns an integer that indicates the relationship
between the two compared strings based on the sorting order. A positive
value for the result indicates that the first string is greater than the
second string. A negative result indicates the first string is smaller,
and zero indicates equality between the strings. Any string, including
an empty string, evaluates to greater than a null reference.
Additional overloads of the
String.Compare
method allow you to indicate whether or not to take case or culture
formatting into account, and to compare substrings within the supplied
strings. For more information on how to compare strings, see
String.Compare Method. Related methods include
String.CompareOrdinal Method and
String.CompareTo Method.
Searching for Strings Within Your Strings
There
are times when it is useful to have data about the characters in your
string and the positions of those characters within your string. A
string can be thought of as an array of characters (
Char instances); you can retrieve a particular character by referencing the index of that character through the
Chars property. For example:
Dim myString As String = "ABCDE"
Dim myChar As Char
myChar = myString.Chars(3) ' myChar = "D"
You can use the
String.IndexOf method to return the index where a particular character is encountered, as in the following example:
Dim myString As String = "ABCDE"
Dim myInteger As Integer
myInteger = myString.IndexOf("D") ' myInteger = 3
In the previous example, the
IndexOf method of
myString
was used to return the index corresponding to the first instance of the character "C" in the string.
IndexOf
is an overloaded method, and the other overloads provide methods to
search for any of a set of characters, or to search for a string within
your string, among others. The Visual Basic .NET command
InStr also allows you to perform similar functions. For more information of these methods, see
String.IndexOf Method and
InStr Function. You can also use the
String.LastIndexOf Method to search for the last occurrence of a character in your string.
Creating New Strings from Old
When
using strings, you may want to modify your strings and create new ones.
You may want to do something as simple as convert the entire string to
uppercase, or trim off trailing spaces; or you may want to do something
more complex, such as extracting a substring from your string. The
System.String class provides a wide range of options for modifying, manipulating, and making new strings out of your old ones.
To combine multiple strings, you can use the concatenation operators (
& or
+). You can also use the
String.Concat Method to concatenate a series of strings or strings contained in objects. An example of the
String.Concat method follows:
Dim aString As String = "A"
Dim bString As String = "B"
Dim cString As String = "C"
Dim dString As String = "D"
Dim myString As String
' myString = "ABCD"
myString = String.Concat(aString, bString, cString, dString)
You can convert your strings to all uppercase or all lowercase strings using either the Visual Basic .NET functions
UCase Function and
LCase Function or the
String.ToUpper Method and
String.ToLower Method methods. An example is shown below:
Dim myString As String = "UpPeR oR LoWeR cAsE"
Dim newString As String
' newString = "UPPER OR LOWER CASE"
newString = UCase(myString)
' newString = "upper or lower case"
newString = LCase(myString)
' newString = "UPPER OR LOWER CASE"
newString = myString.ToUpper
' newString = "upper or lower case"
newString = myString.ToLower
The
String.Format method and the Visual Basic .NET
Format command can generate a new string by applying formatting to a given string. For information on these commands, see
Format Function or
String.Format Method.
You
may at times need to remove trailing or leading spaces from your
string. For instance, you might be parsing a string that had spaces
inserted for the purposes of alignment. You can remove these spaces
using the
String.Trim Method function, or the Visual Basic .NET
Trim function. An example is shown:
Dim spaceString As String = _
" This string will have the spaces removed "
Dim oneString As String
Dim twoString As String
' This removes all trailing and leading spaces.
oneString = spaceString.Trim
' This also removes all trailing and leading spaces.
twoString = Trim(spaceString)
If you only want to remove trailing spaces, you can use the
String.TrimEnd Method or the
RTrim function, and for leading spaces you can use the
String.TrimStart Method or the
LTrim function. For more details, see
LTrim, RTrim, and Trim Functions functions.
The
String.Trim
functions and related functions also allow you to remove instances of a
specific character from the ends of your string. The following example
trims all leading and trailing instances of the "#" character:
Dim myString As String = "#####Remove those!######"
Dim oneString As String
OneString = myString.Trim("#")
You can also add leading or trailing characters by using the
String.PadLeft Method or the
String.PadRight Method.
If you have excess characters within the body of your string, you can excise them by using the
String.Remove Method, or you can replace them with another character using the
String.Replace Method. For example:
Dim aString As String = "This is My Str@o@o@ing"
Dim myString As String
Dim anotherString As String
' myString = "This is My String"
myString = aString.Remove(14, 5)
' anotherString = "This is Another String"
anotherString = myString.Replace("My", "Another")
You can use the
String.Replace method to replace either individual characters or strings of characters. The Visual Basic .NET
Mid Statement can also be used to replace an interior string with another string.
You can also use the
String.Insert Method to insert a string within another string, as in the following example:
Dim aString As String = "This is My Stng"
Dim myString As String
' Results in a value of "This is My String".
myString = aString.Insert(13, "ri")
The first parameter that the
String.Insert method takes is
the index of the character the string is to be inserted after, and the
second parameter is the string to be inserted.
You can concatenate an array of strings together with a separator string by using the
String.Join Method. Here is an example:
Dim shoppingItem(2) As String
Dim shoppingList As String
shoppingItem(0) = "Milk"
shoppingItem(1) = "Eggs"
shoppingItem(2) = "Bread"
shoppingList = String.Join(",", shoppingItem)
The value of
shoppingList
after running this
code is "Milk,Eggs,Bread". Note that if your array has empty members,
the method still adds a separator string between all the empty instances
in your array.
You can also create an array of strings from a single string by using the
String.Split Method.
The following example demonstrates the reverse of the previous example:
it takes a shopping list and turns it into an array of shopping items.
The separator in this case is an instance of the
Char data type; thus it is appended with the literal type character
c.
Dim shoppingList As String = "Milk,Eggs,Bread"
Dim shoppingItem(2) As String
shoppingItem = shoppingList.Split(","c)
The Visual Basic .NET
Mid Function can be used to generate substrings of your string. The following example shows this functions in use:
Dim aString As String = "Left Center Right"
Dim rString, lString, mString As String
' rString = "Right"
rString = Mid(aString, 13)
' lString = "Left"
lString = Mid(aString, 1, 4)
' mString = "Center"
mString = Mid(aString, 6,6)
Substrings of your string can also be generated using the
String.Substring Method. This method takes two arguments: the character index where the substring is to start, and the length of the substring. The
String.Substring method operates much like the
Mid function. An example is shown below:
Dim aString As String = "Left Center Right"
Dim subString As String
' subString = "Center"
subString = aString.SubString(5,6)
There is one very important difference between the
String.SubString method and the
Mid function. The
Mid function takes an argument that indicates the character position for the substring to start, starting with position 1. The
String.SubString
method takes an index of the character in the string at which the
substring is to start, starting with position 0. Thus, if you have a
string "ABCDE", the individual characters are numbered 1,2,3,4,5 for use
with the
Mid function, but 0,1,2,3,4 for use with the
System.String function.