This chapter is from the book

Regardless of what type of data you're working with or what kind of application you're creating, you will undoubtedly need to work with strings. No matter how the data is stored, the end user always deals in human-readable text. As such, knowing how to work with strings is part of the essential knowledge that any .NET developer needs to make rich and compelling applications.

In addition to showing you how to work with strings in the .NET Framework, this chapter will also introduce you to regular expressions. Regular expressions are format codes that not only allow you to verify that a particular string matches a given format, but you can also use regular expressions to extract meaningful information from what otherwise might be considered free-form text, such as extracting the first name from user input, or the area code from a phone number input, or the server name from a URL.

Working with Strings

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 String

Before 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 Strings

One 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.

Table 3.1. Custom DateTime Format Specifiers

Specifier

Description

d

Displays the current day of the month.

dd

Displays the current day of the month, where values < 10 have a leading zero.

ddd

Displays the three-letter abbreviation of the name of the day of the week.

dddd(+)

Displays the full name of the day of the week represented by the given DateTime value.

f(+)

Displays the x most significant digits of the seconds value. The more f's in the format specifier, the more significant digits. This is total seconds, not the number of seconds passed since the last minute.

F(+)

Same as f(+), except trailing zeros are not displayed.

g

Displays the era for a given DateTime (for example, "A.D.")

h

Displays the hour, in range 1–12.

hh

Displays the hour, in range 1–12, where values < 10 have a leading zero.

H

Displays the hour in range 0–23.

HH

Displays the hour in range 0–23, where values < 10 have a leading zero.

m

Displays the minute, range 0–59.

mm

Displays the minute, range 0–59, where values < 10 have a leading zero.

M

Displays the month as a value ranging from 1–12.

MM

Displays the month as a value ranging from 1–12 where values < 10 have a leading zero.

MMM

Displays the three-character abbreviated name of the month.

MMMM

Displays the full name of the month.

s

Displays the number of seconds in range 0–59.

ss(+)

Displays the number of seconds in range 0–59, where values < 10 have a leading 0.

t

Displays the first character of the AM/PM indicator for the given time.

tt(+)

Displays the full AM/PM indicator for the given time.

y/yy/yyyy

Displays the year for the given time.

z/zz/zzz(+)

Displays the timezone offset for the given time.

Take a look at the following lines of code, which demonstrate using string format specifiers to create custom-formatted date and time strings:

If multiple format sections are defined, conditional behavior can be implemented for even more fine-grained control of the numeric formatting:

Two sections— If you have two formatting sections, the first section applies to all positive (including 0) values. The second section applies to negative values. This is extremely handy when you want to enclose negative values in parentheses as is done in many accounting software packages.

Three sections— If you have three formatting sections, the first section applies to all positive (not including 0) values. The second section applies to negative values, and the third section applies to zero.

The following few lines of code illustrate how to use custom numeric format specifiers.

The output generated by the preceding code is shown in the following code:

$59.99
($569.99)
nuttin
23%

Manipulating and Comparing Strings

In 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.

Table 3.3. Commonly Used String Instance Methods

Method

Description

CompareTo

Compares this string instance with another string instance.

Contains

Returns a Boolean indicating whether the current string instance contains the given substring.

CopyTo

Copies a substring from within the string instance to a specified location within an array of characters.

EndsWith

Returns a Boolean value indicating whether the string ends with a given substring.

Equals

Indicates whether the string is equal to another string. You can use the '==' operator as well.

IndexOf

Returns the index of a substring within the string instance.

IndexOfAny

Returns the first index occurrence of any character in the substring within the string instance.

PadLeft

Pads the string with the specified number of spaces or another Unicode character, effectively right-justifying the string.

PadRight

Appends a specified number of spaces or other Unicode character to the end of the string, creating a left-justification.

Remove

Deletes a given number of characters from the string.

Replace

Replaces all occurrences of a given character or string within the string instance with the specified replacement.

Split

Splits the current string into an array of strings, using the specified character as the splitting point.

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 StringBuilder

As 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: