Chapter 9

Strings and Regular Expressions


  • Building strings
  • Formatting expressions
  • Using regular expressions


The code downloads for this chapter are found at on the Download Code tab. The code for this chapter is divided into the following major examples:

  • Encoder.cs
  • Encoder2.cs
  • FormattableVector.cs
  • RegularExpressionPlayground.cs
  • StringEncoder.cs

Strings have been used consistently since the beginning of this book, but you might not have realized that the stated mapping that the string keyword in C# actually refers to is the System.String .NET base class. System.String is a very powerful and versatile class, but it is by no means the only string-related class in the .NET armory. This chapter begins by reviewing the features of System.String and then looks at some nifty things you can do with strings using some of the other .NET classes — in particular those in the System.Text and System.Text.RegularExpressions namespaces. This chapter covers the following areas:

  • Building strings — If you’re performing repeated modifications on a string — for example, to build a lengthy string prior to displaying it or passing it to some other method or application — the String class can be very inefficient. When you find yourself in this kind of situation, another class, System.Text.StringBuilder, is more suitable because it has been designed exactly for this scenario.

Get Professional C# 2012 and .NET 4.5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.