Working with Strings


In the following sections, you examine in detail the methods and properties that the .NET framework provides for working with strings.

First, you look at various methods for formatting strings. You learn how to format currencies, dates, and times and control exactly how a string is displayed.

Next, you examine the methods and properties of the String class itself for manipulating the contents of your strings.

Finally, you learn about the StringBuilder class and how to exploit this class to work efficiently with large strings.

Formatting Strings

The String class includes a Format method that you can use to format one or more arguments. For example, in the following code, the Format method formats the output of a string variable named strUsername :

 
 Dim strUsername As String strUsername = "aspguy" Response.Write( String.Format( "Your username is {0}", strUsername ) ) 

When these statements are executed, the following string is output:

 
 Your username is aspguy 

Two parameters are passed to the Format method. The first parameter represents a format string. In this case, the format string is "Your username is {0}" . The {0} characters represent a placeholder. The second parameter passed to the Format method is substituted for this placeholder.

You can list up to three arguments with the Format method, as shown here:

 
 Dim strSentence, strPerson, strPlace, strThing As String strPerson = "Bill" strPlace = "the store" strThing = "some eggs" strSentence = String.Format( "{0} went to {1} and bought {2}", strPerson, strPlace, strThing ) Response.Write( strSentence ) 

When the preceding statements are executed, the following sentence is output:

 
 Bill went to the store and bought some eggs 

You also can specify an optional minimum width used when displaying the output of each placeholder. You do so by adding a comma, followed by a number specifying a width, like this:

 
 Response.Write( String.Format( "<pre>{0,10}</pre>", "eggs" ) ) 

This format string displays the argument with a minimum of 10 spaces. The HTML <pre> tag is included here because HTML normally ignores spaces. The <pre> tag forces spaces to be interpreted literally.

By default, when you specify a minimum width, the argument is right-aligned. If you prefer to left-align the output, use a negative value for the width like this:

 
 Response.Write( String.Format( "<pre>{0,-10}</pre>", "eggs" ) ) 

This statement pads the output with a minimum of 10 spaces and left-aligns the argument represented by the placeholder.

NOTE

If you need to pass more than three arguments to the Format method, you can pass an array of arguments as the second parameter.


Formatting Numbers

The .NET framework includes several format specifiers that you can use to format the output of numbers. You can use these specifiers with the Format method discussed in the preceding section or with the ToString method.

The following list describes the format specifiers used for formatting numbers:

  • D or d ” Formats a number as a decimal number; for example, 3200

  • E or e ” Formats a number as an exponential number using scientific notation; for example, 3.200100e+004

  • F or f ” Formats a number as a fixed-point number; for example, 32001.00

  • G or g ” Formats a number as a decimal number or as an exponential number (represents the number in the shortest possible way); for example, 32001

  • N or n ” Formats a number using number formatting; for example, 32,001.00

  • H or h ” Formats a number as a hexadecimal number; for example, 7d01

The page in Listing 24.6 demonstrates how the different specifiers work with the ToString method to format both an Integer and Decimal number.

Listing 24.6 FormatNumber.aspx
 <% Dim intNum As Integer Dim decNum As Decimal intNum = 32001 decNum = 32001.9099 ' Decimal Format Response.Write( intNum.ToString( "d" ) ) ' => Displays 32001 ' Exponential Format Response.Write( intNum.ToString( "e" ) ) ' => Displays 3.200100e+004 Response.Write( decNum.ToString( "e" ) ) ' => Displays 3.200191e+004 ' Fixed-Point Format Response.Write( intNum.ToString( "f" ) ) ' => Displays 32001.00 Response.Write( decNum.ToString( "f" ) ) ' => Displays 32001.91  ' General Format Response.Write( intNum.ToString( "g" ) ) ' => Displays 32001 Response.Write( decNum.ToString( "g" ) ) ' => Displays 32001.9099 ' Number Format Response.Write( intNum.ToString( "n" ) ) ' => Displays 32,001.00 Response.Write( decNum.ToString( "n" ) ) ' => Displays 32,001.91 ' HexaDecimal Format Response.Write( intNum.ToString( "x" ) ) ' => Displays 7d01 %> 

The C# version of this code can be found on the CD-ROM.

You also can use any of these format specifiers with the Format method discussed in the preceding section. The following statement uses the number specifier :

 
 Response.Write( String.Format( "Quantity: {0:n}", 12300.00 ) ) 

The n that follows the placeholder indicates that the number should be formatted using the number specifier. This statement outputs the following:

 
 Quantity: 12,300.00 

When displaying numbers, you also can indicate the number of digits to display by listing a number immediately after the format specifier. For example, the following statement displays an integer value with extra leading zeros:

 
 Response.Write( 6.ToString( "d10" ) ) ' => Displays 0000000006 

When you append a number to any of the other number specifiers, the number represents the number of digits to display after the decimal point, as shown here:

 
 Dim intNum As Integer intNum = 32 Response.Write( intNum.ToString( "n10" ) ) ' => Displays 32.0000000000 

NOTE

If you need very precise control over the formatting of numbers, you can use picture format strings. To learn more details, see the .NET Framework Software Development Kit Documentation.


Formatting Currency

The .NET framework includes a special format specifier for formatting currency amounts. You can use either the C or c format specifier with the Format or ToString method to display a number as currency.

The following statements illustrate how to format a decimal number with the ToString method:

 
 Dim decPrice As Decimal decPrice = 1233.99 Response.Write( decPrice.ToString( "c" ) ) 

This Response.Write statement outputs the following string:

 
 ,233.99 

You also can use the currency format specifier with the Format method like this:

 
 Response.Write( String.Format( "Price: {0:c}", 2321.65 ) ) 

This statement outputs the following:

 
 Price: ,321.65 

By default, two decimal places are displayed. If you want to display a different number of decimal places, you can append a number to the currency specifier like this:

 
 Dim decPrice As Decimal decPrice = 2321.65 Response.Write( decPrice.ToString( "c0" ) ) ' => Displays ,322 Response.Write( String.Format( "Price: {0:c5}", 2321.65 ) ) ' => Displays ,321.65000 

The ToString method displays the price with no decimal places (notice that the price is automatically rounded up). The Format method displays the price with five decimal places.

Formatting Dates and Times

The .NET framework includes the following format specifiers for displaying dates and times:

  • d ” Displays a short date; for example, 2/13/2001

  • D ” Displays a long date; for example, Tuesday, February 13, 2001

  • f ” Displays a long date and short time; for example, Tuesday, February 13, 2001 3:40 PM

  • F ” Displays a long date and long time; for example, Tuesday, February 13, 2001 3:41:04 PM

  • g ” Displays a short date and short time; for example, 2/13/2001 3:42 PM

  • G ” Displays a short date and long time; for example, 2/13/2001 3:42:52 PM

  • M or m ” Displays month and day; for example, February 13

  • R or r ” Displays in RFC 1123 format; for example, Tue, 13 Feb 2001 15:44:52 GMT

  • s ” Displays in ISO 8601 format; for example, 2001-02-13T15:45:55

  • t ” Displays a short time; for example, 3:47 PM

  • T ” Displays a long time; for example, 3:47:37 PM

  • u ” Displays in ISO 8601 format using universal time; for example, 2001-02-13 15:48:41Z

  • U ” Displays a date and time using universal time; for example, Tuesday, February 13, 2001 11:49:51 PM

  • Y or y ” Displays a month and year; for example, February, 2001

The page in Listing 24.7 illustrates how you can use the date and time specifiers with the ToString method.

Listing 24.7 FormatDateTime.aspx
 <% Dim dtmDate As DateTime dtmDate = DateTime.Now() ' Short Date Response.Write( dtmDate.ToString( "d" ) ) ' => Displays 2/13/2001 ' Long Date Response.Write( dtmDate.ToString( "D" ) ) ' => Displays Tuesday, February 13, 2001  ' Long Date and Short Time Response.Write( dtmDate.ToString( "f" ) ) ' => Displays Tuesday, February 13, 2001 3:40 PM ' Long Date and Long Time Response.Write( dtmDate.ToString( "F" ) ) ' => Displays Tuesday, February 13, 2001 3:41:04 PM ' Short Date and Short Time Response.Write( dtmDate.ToString( "g" ) ) ' => Displays 2/13/2001 3:42 PM ' Short Date and Long Time Response.Write( dtmDate.ToString( "G" ) ) ' => Displays 2/13/2001 3:42:52 PM ' Month and Day Response.Write( dtmDate.ToString( "M" ) ) ' => Displays February 13 ' RFC 1123 Response.Write( dtmDate.ToString( "R" ) ) ' => Displays Tue, 13 Feb 2001 15:44:52 GMT ' ISO 8601 Response.Write( dtmDate.ToString( "s" ) ) ' => Displays 2001-02-13T15:45:55 ' Short Time Response.Write( dtmDate.ToString( "t" ) ) ' => Displays 3:47 PM ' Long Time Response.Write( dtmDate.ToString( "T" ) ) ' => Displays 3:47:37 PM ' Universal ISO 8601 Response.Write( dtmDate.ToString( "u" ) ) ' => Displays 2001-02-13 15:48:41Z ' Universal Time Response.Write( dtmDate.ToString( "U" ) ) ' => Displays Tuesday, February 13, 2001 11:49:51 PM ' Month and Year Response.Write( dtmDate.ToString( "Y" ) ) ' => Displays February, 2001 %> 

The C# version of this code can be found on the CD-ROM.

You also can use the date and time format specifiers with the Format method. For example, the following statement displays the current date using a long date:

 
 Response.Write( String.Format( "Today is {0:D}", DateTime.Now ) ) 

This statement displays output similar to the following:

 
 Today is Tuesday, February 13, 2003 
Formatting Strings for Different Cultures

Different cultures format numbers, dates, and times using different conventions. For example, in the United States, the currency amount of 9999.99 is formatted like this:

 
 ,999.99 

In Germany, on the other hand, this same currency amount is formatted like this:

 
 9.999,99 DM 

Imagine that you decide to sell products from your Web site internationally. If you decide to do so, you need a way to format currency amounts for different countries .

The .NET framework includes classes for formatting strings for different cultures. These classes inhabit the System.Globalization namespace. The most important of these classes is CultureInfo .

You can use the CultureInfo class with the ToString method to format a string for a particular culture. For example, the following statements display a currency amount using the culture information for Germany:

 
 <%@ Import Namespace="System.Globalization" %> <% Dim objCulture As CultureInfo Dim decPrice As Decimal decPrice = 9999.99 objCulture = New CultureInfo( "de-DE" ) Response.Write( decPrice.ToString( "c", objCulture ) ) %> 

Notice that the System.Globalization namespace needs to be imported at the top of the page. You must import the namespace before you can use the CultureInfo class.

When the CultureInfo class is initialized, it is initialized with the CultureInfo name for Germany ( de-DE ). The CultureInfo class is then used with the ToString method to display a currency amount using a format appropriate to Germany.

NOTE

A list of all the CultureInfo names is included with the documentation for the CultureInfo class in the .NET Framework SDK Documentation.


The page in Listing 24.8 displays the list of CultureInfo names supported by your server. It also displays a currency amount, numeric amount, and date-time value formatted according to the conventions of each culture (see Figure 24.1).

Listing 24.8 CultureInfo.aspx
 <%@ Import Namespace="System.Globalization" %> <Script Runat="Server"> Dim decPrice As Decimal = 9999.99 Dim decQuantity As Decimal = 9999.99 Sub Page_Load   dgrdCultures.DataSource = CultureInfo.GetCultures( CultureTypes.InstalledWin32Cultures )   dgrdCultures.DataBind() End Sub </Script> <html> <head><title>CultureInfo.aspx</title></head> <body> <asp:DataGrid   ID="dgrdCultures"   AutoGenerateColumns="False"   CellPadding="4"   HeaderStyle-Font-Bold="True"   HeaderStyle-BackColor="Turquoise"   AlternatingItemStyle-BackColor="AliceBlue"   Runat="Server"> <Columns>   <asp:BoundColumn     HeaderText="EnglishName"     DataField="EnglishName" />   <asp:BoundColumn     HeaderText="Name"     DataField="Name" />   <asp:TemplateColumn HeaderText="Currency Format">     <itemTemplate>     <%# decPrice.ToString( "c", Container.DataItem ) %>     </itemTemplate>   </asp:TemplateColumn>   <asp:TemplateColumn HeaderText="Number Format">     <itemTemplate>     <%# decQuantity.ToString( "n", Container.DataItem ) %>     </itemTemplate>   </asp:TemplateColumn>   <asp:TemplateColumn HeaderText="Date/Time Format">     <itemTemplate>     <%# DateTime.Now.ToString( "F", Container.DataItem ) %>     </itemTemplate>   </asp:TemplateColumn> </Columns> </asp:DataGrid> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Figure 24.1. Displaying culture information.

graphics/24fig01.jpg

In the Page_Load subroutine in Listing 24.8, the GetCultures method retrieves a list of all the installed cultures on the current server. This list is bound to a DataGrid control.

The DataGrid control" displays the English name of each item in the list of cultures, the abbreviated name, and templates that display a currency amount, number, and date formatted for each culture.

Using String Methods and Properties

The String class contains a rich set of properties and methods that you can use to manipulate the contents of a string. The following sections provide an overview of these properties and methods.

NOTE

The Visual Basic language itself includes a number of methods for manipulating strings. For more information see the Visual Basic Language and Run-Time Reference in the .NET Framework SDK Documentation.


Comparing Two Strings

The easiest way to compare two strings is to use the equality operator like this:

 
 If "Aardvark" = "Turtle" Then   Response.Write( "They Match!" ) Else   Response.Write( "They Don't Match!" ) End If 

If the string Aardvark matches the string Turtle , the message They Match! is displayed.

If you want to make life more difficult for yourself, you also can compare strings by using the Compare method like this:

 
 If String.Compare( "Aardvark", "Turtle" ) = 0 Then   Response.Write( "They Match!" ) Else   Response.Write( "They Don't Match!" ) End If 

If the two strings compared by the Compare method match, the method returns the value . This example accomplishes the same thing as the previous example, with a little more work.

There are a couple of advantages to using the Compare method. The first, and probably most significant advantage, is that it enables you to perform comparisons that are not case sensitive. The Compare method enables you to specify a third, Boolean argument, as shown here, that indicates whether to perform a case-sensitive comparison:

 
 If String.Compare( "AARDVARK", "aardvark", True ) = 0 Then   Response.Write( "They Match!" ) Else   Response.Write( "They Don't Match!" ) End If 

In this example, the Compare method reports that the two strings match, even though one string is uppercase and one string is lowercase. The third parameter to the Compare method, True , indicates that a comparison that is not case sensitive should be performed.

The second advantage of the Compare method is that it enables you to compare whether one string is greater or less than another. Greater than and less than mean alphabetically greater than and less than. If the first string passed to the Compare method would appear earlier in a dictionary than the second string, the Compare method returns the value -1 . If the strings match, the Compare method returns . Finally, if the first string would appear later in a dictionary than the second string, Compare returns the value 1 .

Removing Characters from a String

When users enter information into HTML forms, they often add extra spaces. These extra spaces can cause problems. For example, if a user accidentally enters additional spaces when entering a password, the password might not be correctly matched.

To get around this problem, you should always be careful to trim away extraneous whitespace. The String class includes three Trim methods that perform this very function:

  • Trim

  • TrimStart

  • TrimEnd

By default, all three methods remove whitespace from a string. The Trim method removes any whitespace at the beginning and end of a string, the TrimStart method removes any whitespace at the beginning of a string, and the TrimEnd method removes any whitespace at the end of a string.

NOTE

Whitespace includes carriage returns, spaces, and tabs. You can determine whether any character is considered to be whitespace by using the IsWhiteSpace method of the Char class.


The following statements, for example, trim all the spaces and the carriage return from a string named strMessage :

 
 Dim strString As String = " Hello!  " & vbNewline Response.Write( strString.Trim() ) 

You also can use the Trim methods to remove characters other than whitespace. All three methods accept an array of characters as a parameter. The array contains the characters to trim away.

The following statement, for example, trims away all (lowercase) vowels from the beginning of the string:

 
 Dim arrVowels() As Char = {"a","e","i","o","u"} Dim strString As String = "aardvark" Response.Write( strString.TrimStart( arrVowels ) ) 

You also can use the Remove method to remove characters from a string. This method removes a certain number of characters starting at a certain position in a string. For example, the following call to the Remove method removes characters starting at index position 2 and continuing for three characters:

 
 Dim strString As String = "aardvark" Response.Write( strString.Remove( 2, 3 ) ) 

After the Remove method is called, this statement outputs the value aaark .

Finding Characters in a String

You can search for a particular string within a string by using the IndexOf method, which returns the index position of the target string. For example, the following statements check whether aardvark appears in a string:

 
 Dim strString As String strString = "The slow moving aardvark" If strString.IndexOf( "aardvark" ) > 0  Then   Response.Write( "Found aardvark!" ) Else   Response.Write( "No aardvark found!" ) End If 

You can use the IndexOfAny method with an array of characters. The following statement returns the position of the first lowercase vowel in the string:

 
 Dim arrVowels() As Char = {"a","e","i","o","u"} Dim strString As String strString = "The slow moving aardvark" Response.Write( strString.IndexOfAny( arrVowels  ) ) 

The IndexOfAny method in this statement returns the value 2 because the letter e appears as the third character in the string (the IndexOfAny method is zero-based ).

A variation of the IndexOf method, called LastIndexOf , enables you to find the last matching string in a string. (There is also a LastIndexOfAny method that works with an array of characters.)

 
 Dim strString As String strString = "The slow moving aardvark" Response.Write( strString.LastIndexOf( "ar" ) ) 

In this example, the LastIndexOf method returns the value 21 because the last occurrence of the string ar appears 21 characters from the beginning of the string.

Two other methods of the String class should be mentioned in this context: StartsWith and EndsWith . These methods enable you to match a string at the beginning and end of a string:

 
 Dim strString As String strString = "http://www.superexpert.com" If strString.StartsWith( "http://" ) and strString.EndsWith( ".com" ) Then   Response.Write( "Thanks for entering your company URL!" ) End If 

Here, the StartsWith and EndsWith methods check whether a string starts and ends with particular characters.

Modifying a String

The String class includes several methods for modifying a string. For example, you can use the Replace method to substitute new strings for parts of strings:

 
 Dim strString As String strString = "The slow-moving aardvark" strString = strString.Replace( "aardvark", "turtle" ) Response.Write( strString ) 

When you execute these statements, the phrase The slow-moving turtle is displayed.

You can insert a new string into an existing string by using the Insert method as follows:

 
 Dim strString As String strString = "The slow-moving aardvark" strString = strString.Insert( 16, "but happy " ) Response.Write( strString ) 

When the Insert method is executed in this example, the phrase The slow-moving but happy aardvark is displayed.

You also can extract a substring from a string by using the Substring method like this:

 
 Dim strString As String strString = "The slow-moving aardvark" strString = strString.Substring( 4, 11 ) Response.Write( strString ) 

The Substring method in this example extracts the phrase slow-moving . The Substring method grabs the string starting at index position 4 with a length of 11 characters.

You also can use the ToUpper and ToLower methods to modify the case of a string. The following example demonstrates both methods:

 
 Dim strString As String strString = "The slow-moving aardvark" Response.Write( strString.ToUpper ) Response.Write( strString.ToLower ) 

The ToUpper method returns THE SLOW-MOVING AARDVARK and the ToLower method returns the slow-moving aardvark .

Splitting and Joining Strings

You can split a string into multiple little strings by using the Split method. For example, the following statement splits a sentence into individual words and displays each word in a bulleted list:

 
 Dim strString As String Dim arrArray() As String Dim strItem As String strString = "The slow-moving aardvark" arrArray = strString.Split() For Each strItem in arrArray   Response.Write( "<li>" & strItem ) Next 

By default, the Split method splits a string wherever whitespace occurs (spaces, carriage returns, tabs, and so on). The method returns an array in which each element represents one of the resulting strings.

You also can pass a character, or array of characters, to the Split method. For example, the following statement splits a sentence wherever the letter v occurs:

 
 Dim strString As String Dim arrArray() As String Dim strItem As String strString = "The slow-moving aardvark" arrArray = strString.Split( "v" ) For Each strItem in arrArray   Response.Write( "<li>" & strItem ) Next 

After the Split method is called, the following items are displayed:

  • The slow-mo

  • ing aard

  • ark

You can perform the opposite operation by using the Join method, which joins together all the elements in an array into a single string like this:

 
 Dim arrArray() As String = {"The","slow-moving","aardvark"} Response.Write( String.Join( " ", arrArray ) ) 

The first statement creates a three-element array. The second statement joins all the elements together, using a space as a separator, and displays The slow-moving aardvark .

Using the StringBuilder Class

If you need to work with large strings ”resumes, product descriptions, the text of the Declaration of Independence ”you should consider using the methods and properties of the StringBuilder class. This class, unlike the String class, can more efficiently manage memory when representing a string.

You can create a new instance of the StringBuilder class from an existing string like this:

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder( "The slow-moving aardvark" ) 

When you create a new instance of the StringBuilder class, it is created with a certain capacity that represents the number of characters the StringBuilder can contain.

By default, a StringBuilder has a capacity of 16 characters. However, the capacity automatically grows to handle the number of characters contained in the class. If you know that you'll be working with a large string, you can specify the capacity when you initialize the StringBuilder like this:

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder( "The slow-moving aardvark", 1000 ) 

This StringBuilder is created with an initial capacity of 1,000 characters.

If you're working with truly huge strings, you might want to check whether the server has enough memory to handle the size of the strings. You can attempt to initialize a string with a particular capacity by using the EnsureCapacity method like this:

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder( "The slow-moving aardvark" ) objStringBuilder.EnsureCapacity( 99999 ) 

This example attempts to create a StringBuilder with a capacity of 99,999 characters, which is the minimum capacity. Calling the EnsureCapacity method might actually reserve more characters than the number requested .

Appending Strings to a StringBuilder

After you create an instance of a StringBuilder , you can add characters to it by using the Append method. For example, the following example initializes a StringBuilder with the text The slow-moving aardvark and appends the text and the happy turtle and bought some eggs to the end of the StringBuilder :

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder( "The slow-moving aardvark" ) objStringBuilder.Append( " and the happy turtle" ) objStringBuilder.Append( " bought some eggs" ) Response.Write( objStringBuilder.ToString() ) 

You also can add a formatted string to a StringBuilder . The following example uses a For...Next loop to append 10 strings to the StringBuilder . Each string is formatted with the format string "<p> counter = {0:n}" :

 
 Dim objStringBuilder As StringBuilder Dim intCounter As Integer objStringBuilder = New StringBuilder() For intCounter = 1 to 10   objStringBuilder.AppendFormat( "<p> counter = {0:n}", intCounter ) Next Response.Write( objStringBuilder.ToString() ) 

This example outputs the following:

 
 counter = 1.00 counter = 2.00 counter = 3.00 counter = 4.00 counter = 5.00 counter = 6.00 counter = 7.00 counter = 8.00 counter = 9.00 counter = 10.00 

NOTE

To learn more details about using format strings, see the section "Formatting Strings" earlier in this chapter.


Inserting and Removing Strings with a StringBuilder

The StringBuilder Append method appends strings only at the end of a StringBuilder . If you need to add strings to other parts of a StringBuilder , you should use the Insert method.

The following example adds a string to the middle of a StringBuilder :

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder( "The slow-moving aardvark" ) objStringBuilder.Insert( 4, "happy turtle and the " ) Response.Write( objStringBuilder.ToString() ) 

In this example, the Insert method adds a string at the fourth index position. The StringBuilder displays the string The happy turtle and the slow-moving aardvark .

You also can use the Insert method to add a string multiple times. For example, the following example adds the word very to the StringBuilder 100 times starting at the second index position:

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder( "A very long sentence" ) objStringBuilder.Insert( 2, "very, ", 100 ) Response.Write( objStringBuilder.ToString() ) 

If you need to perform the opposite operation and remove characters from a StringBuilder , you can use the Remove method. The following example removes characters from a StringBuilder starting at position 2 and continuing for five characters:

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder( "A very long sentence" ) objStringBuilder.Remove( 2, 5 ) Response.Write( objStringBuilder.ToString() ) 

This example outputs the string A long sentence .

Replacing Strings with a StringBuilder

If you need to replace one string with another in a StringBuilder , you can use the Replace method like this:

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder( "The slow-moving aardvark went to the store" ) objStringBuilder.Replace( "aardvark", "turtle" ) Response.Write( objStringBuilder.ToString() ) 

This example replaces the string aardvark with the string turtle . The Replace method automatically replaces each and every occurrence of the target string.

Iterating Through the Contents of a StringBuilder

You can march through the contents of a StringBuilder , character by character, by using the Chars and Length properties. The Chars property represents a character at a certain index position, whereas the Length property represents the total number of characters in a StringBuilder .

The following example uses a For...Next loop to loop through each character in a StringBuilder and report whether the character is a digit:

 
 Dim objStringBuilder As StringBuilder Dim chrChar As Char Dim intCounter As Integer objStringBuilder = New StringBuilder( "549-27-7878" ) For intCounter = 0 To objStringBuilder.Length - 1   chrChar = objStringBuilder.Chars( intCounter )   If Char.IsDigit( chrChar ) Then     Response.Write( String.Format( "<p>{0} is a digit", chrChar ) )   End If Next 

This For...Next loop loops through each character in the StringBuilder . If the character is a digit, this fact is reported with a Response.Write statement.

NOTE

The IsDigit method is a member of the .NET Char structure, which includes other methods such as IsWhiteSpace and IsLetter .


You can modify a character represented by the Chars property. The following example converts an uppercase string to a lowercase string:

 
 Dim objStringBuilder As StringBuilder Dim chrChar As Char Dim intCounter As Integer objStringBuilder = New StringBuilder( "ALL IN UPPERCASE!" ) For intCounter = 0 to objStringBuilder.Length - 1   chrChar = objStringBuilder.Chars( intCounter )   chrChar = Char.ToLower( chrChar )   objStringBuilder.Chars( intCounter ) = chrChar Next Response.Write( objStringBuilder.ToString() ) 

Here, each character is retrieved from the StringBuilder and converted to lowercase using the ToLower method of the Char structure.

Converting a StringBuilder to a String

You can display the contents of a StringBuilder by using the ToString method. Because it is a method of the Object class (the grandfather of all objects), it works with any class in the .NET framework.

You can use a special variation of the ToString method with the StringBuilder class. Because a StringBuilder can be used to represent gargantuan strings, you might need to display partial strings from a StringBuilder . You can pass a beginning index and length to the ToString method like this:

 
 Dim objStringBuilder As StringBuilder objStringBuilder = New StringBuilder() objStringBuilder.Insert( 0, "aardvark,", 8999 ) Response.Write( objStringBuilder.ToString( 18, 8 ) ) 

This example creates a StringBuilder that contains the word aardvark 8,999 times. The ToString method displays eight characters from the StringBuilder , starting at the character with an index of 18.



ASP.NET Unleashed
ASP.NET 4 Unleashed
ISBN: 0672331128
EAN: 2147483647
Year: 2003
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net