The String class implements the String data type, which is one of the richest data types in terms of the members it exposes. We have used strings extensively in earlier chapters, but this is a formal discussion of the String data type and all of the functionality it exposes.
To create a new instance of the String class, you simply declare a variable of the String type. You can also initialize it by assigning to the corresponding variable a text value:
Dim title As String = "Visual Basic 2008 Tutorial"
Code language: JavaScript (javascript)
Everything enclosed in double quotes is a string, even if it’s the representation of a number. String objects are immutable: Once created, they can’t be modified. The names of some of the methods of the String class may lead you to think that they change the value of the string, but they don’t; instead, they return a new string. The Replace method, for example, doesn’t replace any characters in the original string, but it creates a new string, replaces some characters, and then returns the new string:
Dim title As String = "Visual Basic 2008 Tutorial"
Dim newTitle As String
newTitle = title.Replace("VB", "Visual Basic")
' to replace the original string use the statement:
title = title.Replace("VB", "Visual Basic")
Code language: PHP (php)
The Replace method, like all other methods of the String class, doesn’t operate directly on the string to which it’s applied. Instead, it creates a new string and returns it as a new string. You can also use Visual Basic’s string-manipulation functions to work with strings. For example, you can replace the string VB with Visual Basic by using the following statement:
newTitle = Replace(title, "VB", "Visual Basic")
Code language: JavaScript (javascript)
Like the methods of the String class, the string-manipulation functions don’t act on the original string; they return a new string.
If you plan to create and manipulate long strings in your code often, use the StringBuilder class instead, which is extremely fast compared to the String class and VB’s string-manipulation functions. This doesn’t mean that the String data type is obsolete, of course. The String class exposes many more methods for handling strings (such as locating a smaller string in a larger one, comparing strings, changing individual characters, and so on). The StringBuilder class, on the other hand, is much more efficient when you build long strings bit by bit, when you need to remove part of a string, and so on. To achieve its speed, however, it consumes considerably more memory than the equivalent String variable. The methods of both classes are presented in the following sections.
Properties
The String class exposes only two properties, the Length and Chars properties, which return a string’s length and its characters, respectively. Both properties are read-only.
Length
The Length property returns the number of characters in the string and is read-only. To find out the number of characters in a string variable, use the following statement:
chars = myString.Length
You can apply the Length property to any expression that evaluates to a string. The following statement formats the current date in long date format (this format includes the day’s and month’s names) and then retrieves the string’s length:
StrLen = Format(Now(), "dddd, MMMM dd, yyyy").Length
Code language: JavaScript (javascript)
The Format() function, which formats numbers and dates, is discussed in Chapter 2, ”The Visual Basic 2008 Language.’’ The function returns a string, so we can call this expression’s Length property.
Chars
The Chars property is an array of characters that holds all the characters in the string. Use this property to read individual characters from a string based on their location in the string (the index of the first character in the array is zero). The Chars array is read-only, and you can’t edit a string by setting individual characters.
The loop detailed in Listing 9.2 rejects strings (presumably passwords) that are fewer than six characters long and don’t contain a special symbol.
Listing 9.2: Validating a Password
Private Function ValidatePassword( _
ByVal password As String) As Boolean
If password.Length < 6 Then
MsgBox( _
"The password must be at least 6 characters long")
Return False
End If
Dim i As Integer
Dim valid As Boolean = False
For i = 0 To password.Length - 1
If Not Char.IsLetterOrDigit(password.Chars(i)) Then
Return True
End If
Next
MsgBox("The password must contain at least one " & _
"character that is not a letter or a digit.")
Return False
End Function
Code language: VB.NET (vbnet)
The code checks the length of the user-supplied string and makes sure that it’s at least six characters long. If not, it issues a warning and returns False. Then it starts a loop that scans all the characters in the string. Each character is accessed by its index in the string. If one of them is not a letter or digit — in which case the IsLetterOrDigit method will return False — the function terminates and returns True to indicate a valid password. If the loop is exhausted, the password argument contains no special symbols, and the function displays another message and returns False.
Methods
All the functionality of the String class is available through methods, which are described next. They are all shared methods: They act on a string and return a new string with the modified value.
Compare
This method compares two strings and returns a negative value if the first string is less than the second, a positive value if the second string is less than the first, and zero if the two strings are equal. Of course, the simplest method of comparing two strings is to use the comparison operators, as shown here:
If name1 < name 2 Then
' name1 is alphabetically smaller than name 2
Else If name 1 > name 2 Then
' name2 is alphabetically smaller than name 1
Else
' name1 is the same as name2
End If
Code language: PHP (php)
The Compare method is overloaded, and the first two arguments are always the two strings to be compared. The method’s return value is 0 if the two strings are equal, 1 if the first string is smaller than the second, and −1 if the second is smaller than the first. The simplest form of the method accepts two strings as arguments:
String.Compare(str1, str2)
Code language: JavaScript (javascript)
The following form of the method accepts a third argument, which is a True/False value and determines whether the search will be case-sensitive (if True) or not:
String.Compare(str1, str2, case)
Code language: JavaScript (javascript)
Another form of the Compare method allows you to compare segments of two strings. Its syntax is as follows:
String.Compare(str1, index1, str2, index2, length)
Code language: JavaScript (javascript)
index1 and index2 are the starting locations of the segment to be compared in each string. The two segments must have the same length, which is specified by the last argument. The following statements return the values highlighted below each:
Debug.WriteLine(str.Compare("the quick brown fox", _
"THE QUICK BROWN FOX"))
-1
Debug.WriteLine(str.Compare("THE QUICK BROWN FOX", _
"the quick brown fox"))
1
Debug.WriteLine(str.Compare("THE QUICK BROWN FOX", _
"THE QUICK BROWN FOX"))
0
Code language: JavaScript (javascript)
If you want to specify a case-sensitive search, append yet another argument and set it to True. The forms of the Compare method that perform case-sensitive searches can accept yet another argument, which determines the CultureInfo object to be used in the comparison. (This argument applies to some combination of characters in foreign languages, such as Turkish.)
CompareOrdinal
The CompareOrdinal method compares two strings similar to the Compare method, but it doesn’t take into consideration the current locale. This method returns zero if the two strings are the same, and a positive or negative value if they’re different. These values, however, are not 1 and −1; they represent the numeric difference between the Unicode values of the first two characters that are different in the two strings.
Concat
This method concatenates two or more strings (places them one after the other) and forms a new string. The simpler form of the Concat method has the following syntax and it is equivalent to the & operator:
newString = String.Concat(string1, string2)
Code language: JavaScript (javascript)
This statement is equivalent to the following:
newString = string1 & string2
A more-useful form of the same method concatenates a large number of strings stored in an array:
newString = String.Concat(strings())
Code language: JavaScript (javascript)
To use this form of the method, store all the strings you want to concatenate into a string array and then call the Concat method. If you want to separate the individual strings with special delimiters, append them to each individual string before concatenating them. Or you can use the Join method discussed later in this section. The Concat method simply appends each string to the end of the previous one. If you want to concatenate very long strings or a large number of strings, you should use the StringBuilder class.
Copy
The Copy method copies the value of one string variable to another. Notice that the value to be copied must be passed to the method as an argument. The Copy method doesn’t apply to the current instance of the String class. Most programmers will use the assignment operator and will never bother with the Copy method.
EndsWith, StartsWith
These two methods return True if their argument ends or starts with a user-supplied substring. The syntax of these methods is as follows:
found = str.EndsWith(string)
found = str.StartsWith(string)
These two methods are equivalent to the Left() and Right() functions, which extract a given number of characters from the left or right end of the string, respectively. The two statements following the declaration of the name variable are equivalent:
Dim name As String = "Visual Basic.NET"
If Left(name, 3) = "Vis" Then ...
If String.StartsWith("Vis") Then ...
Code language: JavaScript (javascript)
Notice that the comparison performed by the StartsWith method is case-sensitive. If you don’t care about the case, you can convert both the string and the substring to uppercase, as in the following example:
If name.ToUpper.StartsWith("VIS") Then ...
Code language: CSS (css)
IndexOf, LastIndexOf
These two methods locate a substring in a larger string. The IndexOf method starts searching from the beginning of the string, and the LastIndexOf method starts searching from the end of the string. Both methods return an integer, which is the order of the substring’s first character in the larger string (the order of the first character is zero).
To locate a string within a larger one, use the following forms of the IndexOf method:
pos = str.IndexOf(searchString)
pos = str.IndexOf(SearchString, startIndex)
pos = str.IndexOf(SearchString, startIndex, endIndex)
The startIndex and the endIndex arguments delimit the section of the string where the search will take place, and pos is an integer variable.
The last three overloaded forms of the IndexOf method search for an array of characters in the string:
str.IndexOf(Char())
str.IndexOf(Char(), startIndex)
str.IndexOf(Char(), startIndex, endIndex)
Code language: CSS (css)
The following statement will return the position of the string Visual in the text of the TextBox1 control or will return −1 if the string isn’t contained in the text:
Dim pos As Integer
pos = TextBox1.IndexOf("Visual")
Code language: PHP (php)
Both methods perform a case-sensitive search, taking into consideration the current locale. To make case-insensitive searches, use uppercase for both the string and the substring. The following statement returns the location of the string visual (or VISUAL, Visual, and even vISUAL) within the text of TextBox1:
Dim pos As Integer
pos = TextBox1.Text.ToUpper.IndexOf("VISUAL")
Code language: PHP (php)
The expression TextBox1.Text is the text on the control and its type is String. First, we apply the method ToUpper to convert the text to uppercase. Then we apply the IndexOf method to this string to locate the first instance of the word VISUAL.
IndexOfAny
This is an interesting method that accepts as an argument an array of arguments and returns the first occurrence of any of the array’s characters in the string. The syntax of the IndexOfAny method is
Dim pos As Integer = str.IndexOfAny(chars)
Code language: PHP (php)
where chars is an array of characters. This method attempts to locate the first instance of any member of the chars array in the string. If the character is found, its index is returned. If not, the process is repeated with the second character, and so on until an instance is found or the array has been exhausted. If you want to locate the first delimiter in a string, call the IndexOfAny method with an array such as the following:
Dim chars() As Char = {"."c, ","c, ";"c, " "c}
Dim mystring As String = "This is a short sentence"
Debug.WriteLine(mystring.IndexOfAny(chars))
Code language: PHP (php)
When the last statement is executed, the value 4 will be printed in the Output window. This is the location of the first space in the string. Notice that the space delimiter is the last one in the chars array.
To locate the first number in a string, pass the nums array to the IndexOfAnymethod, as shown in the following example:
Dim nums() As Char = {"1"c, "2"c, "3"c, "4"c, "5"c, _
"6"c, "7"c, "8"c, "9"c, "0"c}
Code language: PHP (php)
Insert
The Insert method inserts one or more characters at a specified location in a string and returns the new string. The syntax of the Insert method is as follows:
newString = str.Insert(startIndex, subString)
startIndex is the position in the str variable, where the string specified by the second argument will be inserted. The following statement will insert a dash between the second and third characters of the string CA93010.
Dim Zip As String = "CA93010"
Dim StateZip As String
StateZip = Zip.Insert(2, "-")
Code language: JavaScript (javascript)
The StateZip string variable will become CA-93010 after the execution of these statements.
Join
This method joins two or more strings and returns a single string with a separator between the original strings. Its syntax is the following, where separator is the string that will be used as the separator, and strings is an array with the strings to be joined:
newString = String.Join(separator, strings)
Code language: JavaScript (javascript)
If you have an array of many strings and you want to join a few of them, you can specify the index of the first string in the array and the number of strings to be joined by using the following form of the Join method:
newString = String.Join(separator, strings, startIndex, count)
Code language: JavaScript (javascript)
The following statement will create a full path by joining folder names:
Dim path As String
Dim folders(3) As String = {"My Documents", "Business", "Expenses"}
path = String.Join("/", folders)
Code language: JavaScript (javascript)
The value of the path variable after the execution of these statements will be as follows:
My Documents/Business/Expenses
Split
Just as you can join strings, you can split a long string into smaller ones by using the Split method, whose syntax is the following, where delimiters is an array of characters and str is the string to be split:
strings() = String.Split(delimiters, str)
Code language: JavaScript (javascript)
The string is split into sections that are separated by any one of the delimiters specified with the first argument. These strings are returned as an array of strings.
Splitting Strings with Multiple Separators
The delimiters array allows you to specify multiple delimiters, which makes it a great tool for isolating words in a text. You can specify all the characters that separate words in text (spaces, tabs, periods, exclamation marks, and so on) as delimiters and pass them along with the text to be parsed to the Split method.
The statements in Listing 9.3 isolate the parts of a path, which are delimited by a backslash character.
Listing 9.3: Extracting a Path’s Components
Dim path As String = "c:\My Documents\Business\Expenses"
Dim delimiters() As Char = {"\"c}
Dim parts() As String
parts = path.Split(delimiters)
Dim iPart As IEnumerator
iPart = parts.GetEnumerator
While iPart.MoveNext
Debug.WriteLine(iPart.Current.tostring)
End While
Code language: PHP (php)
If the path ends with a slash, the Split method will return an extra empty string. If you want to skip the empty strings, pass an additional argument to the function, which is a member of the StringSplitOptions enumeration: None or RemoveEmptyEntries.
Notice that the parts array is declared without a size. It’s a one-dimensional array that will be dimensioned automatically by the Split method, according to the number of substrings separated by the specified delimiter(s). The second half of the code iterates through the parts of the path and displays them in the Output window.
If you execute the statements of Listing 9.3 (place them in a button’s Click event handler and run the program), the following strings will be printed in the Output window:
c:
My Documents
Business
Expenses
If you add the colon character to the list of delimiters, the first string will be C instead of C:.
Remove
The Remove method removes a given number of characters from a string, starting at a specific location, and returns the result as a new string. Its syntax is the following, where startIndex is the index of the first character to be removed in the str string variable and count is the number of characters to be removed:
newSrting = str.Remove(startIndex, count)
Replace
This method replaces all instances of a specified character (or substring) in a string with a new one. It creates a new instance of the string, replaces the characters as specified by its arguments, and returns this string. The syntax of this method is
newString = str.Replace(oldChar, newChar)
where oldChar is the character in the str variable to be replaced, and newChar is the character to replace the occurrences of oldChar. You can also specify strings instead of characters as arguments to the Replace method. The string after the replacement is returned as the result of the method. The following statements replace all instances of the tab character with a single space. You can change the last statement to replace tabs with a specific number of spaces — usually three, four, or five spaces.
Dim txt, newTxt As String
Dim vbTab As String = vbCrLf
txt = "some text with two tabs"
newTxt = txt.Replace(vbTab, " ")
Code language: JavaScript (javascript)
Use the following statements to replace all instances of VB 2005 in a string with the substring VB 2008:
Dim txt, newTxt As String
txt = "Welcome to VB 2005"
newTxt = txt.Replace("VB 2005", "VB 2008")
Code language: JavaScript (javascript)
PadLeft, PadRight
These two methods align the string left or right in a specified field and return a fixed-length string with spaces to the right (for right-padded strings) or to the left (for left-padded strings). After the execution of these statements
Dim LPString, RPString As String
RPString = "[" & "Learning VB".PadRight(20) & "]"
LPString = "[" & "Learning VB".PadLeft(20) & "]"
Code language: JavaScript (javascript)
the values of the LPString and RPString variables are as follows:
[Learning VB ]
[ Learning VB]
Code language: JSON / JSON with Comments (json)
There are eight spaces to the left of the left-padded string and eight spaces to the right of the right-padded string.
Another form of these methods allows you to specify the character to be used in padding the strings with an additional argument.
You can use the padding methods for visual alignment only if you’re using a monospaced font such as Courier. These two methods can be used to create text files with rows made up of fields that have a fixed length (a common task in transferring data to legacy applications on mainframes).