Home > Articles

Strings and Regular Expressions

This chapter is from the book

This chapter is from the book

In This Chapter

Working with Strings

Working with Regular Expressions

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




Displays the current day of the month.


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


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


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


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.


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


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


Displays the hour, in range 1–12.


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


Displays the hour in range 0–23.


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


Displays the minute, range 0–59.


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


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


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


Displays the three-character abbreviated name of the month.


Displays the full name of the month.


Displays the number of seconds in range 0–59.


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


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


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


Displays the year for the given time.


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:

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.

Table 3.2. Numeric Custom Format Specifiers




The zero placeholder.


The digit placeholder. If the given value has a digit in the position indicated by the # specifier, that digit is displayed in the formatted output.


Decimal point.


Thousands separator.


Percentage specifier. The value being formatted will be multiplied by 100 before being included in the formatted output.


Scientific notation.

'XX' or "XX"

Literal strings. These are included literally in the formatted output without translation in their relative positions.


Section separator for conditional formatting of negative, zero, and positive values.

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.

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));

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


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




Compares this string instance with another string instance.


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


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


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


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


Returns the index of a substring within the string instance.


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


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


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


Deletes a given number of characters from the string.


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


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


Returns a Boolean value indicating whether the string instance starts with the specified string.


Returns a specified portion of the string, given a starting point and length.


Converts the string into an array of characters.


Converts the string into all lowercase characters.


Converts the string into all uppercase characters.


Removes all occurrences of a given set of characters from the beginning and end of the string.


Performs the Trim function, but only on the beginning of the string.


Performs the Trim function, but only on the end of the string.

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(string.Format("The string '{0}' is {1} chars long",
Console.WriteLine(string.Format("Fourth word in sentence is : {0}",
    sourceString.Split(' ')[3]));
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 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:

StringBuilder sb = new StringBuilder();
formatString = "{0:$#,###0.00;($#,###0.00);Zero}";
dVal = 129.99;
sb.AppendFormat(formatString, dVal);
sb.Append("\nThis is a big concatenated string.");

The output of the preceding code looks like the following:

This is a big concatenated string.

Note that the \n from the preceding code inserts a newline character into the string.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020