Chapter 2: Working with Data


Most applications need to manipulate some form of data. The Microsoft .NET Framework provides many techniques that simplify or improve the efficiency of common data manipulation tasks . The recipes in this chapter explore some of these techniques and describe how to

  • Manipulate strings efficiently (recipe 2.1).

  • Represent basic data types using different encoding schemes (recipes 2.2, 2.3, and 2.4).

  • Use regular expressions to validate and manipulate strings (recipes 2.5 and 2.6).

  • Work with dates and times (recipes 2.7 and 2.8).

  • Work with arrays and collections (recipes 2.9, 2.10, and 2.11).

  • Serialize object state and persist it to a file (recipe 2.12).

2.1 Manipulate the Contents of a String Efficiently

Problem

You need to manipulate the contents of a String object and want to avoid the overhead of automatic String creation caused by the immutability of String objects.

Solution

Use the System.Text.StringBuilder class to perform the manipulations and convert the result to a String using the StringBuilder.ToString method.

Discussion

String objects in .NET are immutable, meaning that once created they can't be changed. For example, if you build a String by concatenating a number of characters or smaller strings, the common language runtime (CLR) will create a completely new String object whenever you add a new element to the end of the existing string. This can result in significant overhead if your application performs frequent string manipulation.

The StringBuilder class offers a solution by providing a character buffer and allowing you to manipulate its contents without the runtime creating a new object as a result of every change. You can create a new StringBuilder object that's empty or initialized with the content of an existing String object. You can manipulate the content of the StringBuilder object using overloaded methods that allow you to insert and append string representations of different data types. At any time, you can obtain a String representation of the current content of the StringBuilder by calling StringBuilder.ToString .

Two important properties of the StringBuilder control its behavior as you append new data: Capacity and Length . Capacity represents the size of the StringBuilder buffer, whereas Length represents the length of the buffer's current content. If you append new data that results in the number of characters in the StringBuilder ( Length ) exceeding the capacity of the StringBuilder ( Capacity ), the StringBuilder must allocate a new buffer to hold the data. Used carelessly, this buffer reallocation can negate much of the benefit of using the StringBuilder . If you know the length of data you need to work with, or know an upper limit, you can avoid unnecessary buffer reallocation by specifying the capacity at creation time or setting the Capacity property manually. When setting the Capacity and Length properties, be aware of the following behavior:

  • If you set Capacity to a value less than the value of Length , the Capacity property throws the exception System.ArgumentOutOfRangeException .

  • If you set Length to a value less than the length of the current content, the content is truncated.

  • If you set Length to a value greater than the length of the current content, the buffer is padded with spaces to the specified length. Setting Length to a value greater than Capacity automatically adjusts the Capacity to the same value as the new Length .

The ReverseString method shown here demonstrates the use of the StringBuilder class to reverse a string. If you didn't use the StringBuilder class to perform this operation, it would be significantly more expensive in terms of processing power ” especially as the input string is made longer. The method creates a StringBuilder of the correct capacity to ensure no buffer reallocation is required during the reversal operation.

 public static string ReverseString(string str) {              // Make sure we have a reversible string     if (str == null  str.Length == 1) {                 return str;     }              // Create a StringBuilder object with the required capacity     System.Text.StringBuilder revStr =          new System.Text.StringBuilder(str.Length);     // Loop backward through the source string one character at a      // time and append each character to the StringBuilder     for (int count = str.Length-1; count > -1; count--) {                    revStr.Append(str[count]);     }     // Return the reversed string     return revStr.ToString(); } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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