Being able to work with strings is an essential skill in creating high-quality applications. Even if you are working with numeric or image data, end users need textual feedback. This section of the chapter will introduce you to .NET strings, how to format them, manipulate them and compare them, as well as other useful operations. Introduction to the .NET StringBefore the .NET Framework and the Common Language Runtime (CLR), developers used to have to spend considerable amount of effort working with strings. A reusable library of string routines was a part of virtually every C and C++ programmer's toolbox. It was also difficult to write code that exchanged string data between different programming languages. For example, Pascal stores strings as an in-memory character array, where the first element of the array indicated the length of the string. C stores strings as an in-memory array of characters with a variable length. The end of the string was indicated by the ASCII null character (represented in C as \0). In the .NET Framework, strings are stored as immutable values. This means that when you create a string in C# (or any other .NET language), that string is stored in memory in a fixed size to make certain aspects of the CLR run faster (you will learn more about this in Chapter 16, "Optimizing Your NET 2.0 Code"). As a result, when you do things such as concatenate strings or modify individual characters in a string, the CLR is actually creating multiple copies of your string. Strings in C# are declared in the same way as other value types such as integer or float, as shown in the following examples: string x = "Hello World"; string y; string z = x; Formatting StringsOne of the most common tasks when working with strings is formatting them. When displaying information to users, you often display things like dates, times, numeric values, decimal values, monetary values, or even things like hexadecimal numbers. C# strings all have the ability to display these types of information and much more. Another powerful feature is that when you use the standard formatting tools, the output of the formatting will be localization-aware. For example, if you display the current date in short form to a user in England, the current date in short form will appear different to a user in the United States. To create a formatted string, all you have to do is invoke the Format method of the string class and pass it a format string, as shown in the following code: string formatted = string.Format("The value is {0}", value); The {0} placeholder indicates where a value should be inserted. In addition to specifying where a value should be inserted, you can also specify the format for the value. Other data types also support being converted into strings via custom format specifiers, such as the DateTime data type, which can produce a custom-formatted output using DateTime.ToString("format specifiers"); Table 3.1 illustrates some of the most commonly used format strings for formatting dates, times, numeric values, and more.
Take a look at the following lines of code, which demonstrate using string format specifiers to create custom-formatted date and time strings: DateTime dt = DateTime.Now; Console.WriteLine(string.Format("Default format: {0}", dt.ToString())); Console.WriteLine(dt.ToString("dddd dd MMMM, yyyy g")); Console.WriteLine(string.Format("Custom Format 1: {0:MM/dd/yy hh:mm:sstt}", dt)); Console.WriteLine(string.Format("Custom Format 2: {0:hh:mm:sstt G\\MT zz}", dt)); Here is the output from the preceding code: Default format: 9/24/2005 12:59:49 PM Saturday 24 September, 2005 A.D. Custom Format 1: 09/24/05 12:59:49PM Custom Format 2: 12:59:49PM GMT -06 You can also provide custom format specifiers for numeric values as well. Table 3.2 describes the custom format specifiers available for numeric values.
If multiple format sections are defined, conditional behavior can be implemented for even more fine-grained control of the numeric formatting:
The following few lines of code illustrate how to use custom numeric format specifiers. double dVal = 59.99; double dNeg = -569.99; double zeroVal = 0.0; double pct = 0.23; string formatString = "{0:$#,###0.00;($#,###0.00);nuttin}"; Console.WriteLine(string.Format(formatString, dVal)); Console.WriteLine(string.Format(formatString, dNeg)); Console.WriteLine(string.Format(formatString, zeroVal)); Console.WriteLine(pct.ToString("00%")); The output generated by the preceding code is shown in the following code: $59.99 ($569.99) nuttin 23% Manipulating and Comparing StringsIn addition to displaying strings that contain all kinds of formatted data, other common string-related tasks are string manipulation and comparison. An important thing to keep in mind is that the string is actually a class in the underlying Base Class Library of the .NET Framework. Because it is a class, you can actually invoke methods on a string, just as you can invoke methods on any other class. You can invoke these methods both on string literals or on string variables, as shown in the following code: int x = string.Length(); int y = "Hello World".Length(); Table 3.3 is a short list of some of the most commonly used methods that you can use on a string for obtaining information about the string or manipulating it.
Take a look at the following code, which illustrates some of the things you can do with strings to further query and manipulate them: string sourceString = "Mary Had a Little Lamb"; string sourceString2 = " Mary Had a Little Lamb "; Console.WriteLine(sourceString.ToLower()); Console.WriteLine(string.Format("The string '{0}' is {1} chars long", sourceString,sourceString.Length)); Console.WriteLine(string.Format("Fourth word in sentence is : {0}", sourceString.Split(' ')[3])); Console.WriteLine(sourceString2.Trim()); Console.WriteLine("Two strings equal? " + (sourceString == sourceString2.Trim())); The output of the preceding code looks as follows: mary had a little lamb The string 'Mary Had a Little Lamb' is 22 chars long. Fourth word in sentence is : Little Mary Had a Little Lamb Two strings equal? True Introduction to the StringBuilderAs mentioned earlier, strings are immutable. This means that when you concatenate two strings to form a third string, there will be a short period of time where the CLR will actually have all three strings in memory. So, for example, when you concatenate as shown in the following code: string a = "Hello"; string b = "World"; string c = a + " " + c; You actually end up with four strings in memory, including the space. To alleviate this performance issue with string concatenation as well as to provide you with a tool to make concatenation easier, the .NET Framework comes with a class called the StringBuilder. By using a StringBuilder to dynamically create strings of variable length, you get around the immutable string fact of CLR strings and the code can often become more readable as a result. Take a look at the StringBuilder in action in the following code: StringBuilder sb = new StringBuilder(); sb.Append("Greetings!\n"); formatString = "{0:$#,###0.00;($#,###0.00);Zero}"; dVal = 129.99; sb.AppendFormat(formatString, dVal); sb.Append("\nThis is a big concatenated string."); Console.WriteLine(sb.ToString()); The output of the preceding code looks like the following: Greetings! $129.99 This is a big concatenated string. Note that the \n from the preceding code inserts a newline character into the string. |