O'Reilly logo

C# 2008 Programmer's Reference by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 8. Strings and Regular Expressions

One of the most common data types used in programming is the string. In C#, a string is a group of one or more characters declared using the string keyword. Strings play an important part in programming and are an integral part of our lives — our names, addresses, company names, email addresses, web site URLs, flight numbers, and so forth are all made up of strings. To help manipulate those strings and pattern matching, you use regular expressions, sequences of characters that define the patterns of a string. In this chapter, then, you will:

  • Explore the System.String class

  • Learn how to represent special characters in string variables

  • Manipulate strings with various methods

  • Format strings

  • Use the StringBuilder class to create and manipulate strings

  • Use Regular Expressions to match string patterns

The System.String Class

The .NET Framework contains the System.String class for string manipulation. To create an instance of the String class and assign it a string, you can use the following statements:

String str1;
            str1 = "This is a string";

C# also provides an alias to the String class: string (lowercase "s"). The preceding statements can be rewritten as:

string str1; //---equivalent to String str1;---
            str1 = "This is a string";

You can declare a string and assign it a value in one statement, like this:

string str2 = "This is another string";

In .NET, a string is a reference type but behaves very much like a value type. Consider the following example of a ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required