#33 – The string Type

In addition to many built-in value types, like the numeric types, C# provides a built-in string type.  The string type is a reference type, equivalent to the .NET Framework System.String type.

Strings contain a sequence of Unicode (UTF16) characters, equivalent to an array of char.  Each character takes up exactly 2 bytes.

Strings are immutable, which means that you can’t change a string’s value without destroying the old string and creating a new one.

You can use the index operator [] to access individual characters in the string.  This will normally give you a single character, except for Unicode characters that are above U+FFFF and have to be represented using a surrogate pair.

Here are some examples:

 string msg = "We Love C#!";
 char fourth = msg[3];
 string thisnthat = "this" + "that";   // "thisthat"
string sub = msg.Substring(3, 4);  // "Love"
 string dash = msg.Replace(' ', '-');  // "We-Love-C#!"

 // Split into space-delimited words: "We", "Love", "C#!"
 string[] words = msg.Split(new char[]{' '});

 string concat = msg + " Yes we do.";
 bool foundLove = words[1].ToLower() == "love";

 // Convert to lowercase, find substring
 int findLove = msg.ToLower().IndexOf("love");

 // Iterate
 foreach (char c in msg)
 Console.Write(string.Format("{0}-", c));

 string newPtr = msg;   // Pointer to original string
 string new2 = String.Copy(msg);   // Creates new string instance
 msg = "change";        // But newPtr still pointing to old/orig string