Chapter 3. Pulling Strings

In This Chapter

  • Pulling and twisting a string with C# — just don't string me along

  • Comparing strings

  • Other string operations, such as searching, trimming, splitting, and concatenating

  • Parsing strings read into the program

  • Formatting output strings manually or using the String.Format() method

For many applications, you can treat a string like one of the built-in value-type variable types such as int or char. Certain operations that are otherwise reserved for these intrinsic types are available to strings:

int i = 1;          // Declare and initialize an int.
string s = "abc";   // Declare and initialize a string.

In other respects, as shown in the following example, a string is treated like a user-defined class (I cover classes in Book II ):

string s1 = new String();
string s2 = "abcd";
int lengthOfString = s2.Length;

Which is it — a value type or a class? In fact, String is a class for which C# offers special treatment because strings are so widely used in programs. For example, the keyword string is synonymous with the class name String, as shown in this bit of code:

String s1 = "abcd"; // Assign a string literal to a String obj.
string s2 = s1;     // Assign a String obj to a string variable.

In this example, s1 is declared to be an object of class String (spelled with an uppercase S) whereas s2 is declared as a simple string (spelled with a lowercase s). However, the two assignments demonstrate that string and String are of the same (or compatible) types.

Note

In fact, this same ...

Get C# 2010 All-in-One For Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.