#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

More

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #33 – The string Type

  1. Ron Ripperger says:

    For those coming from C++, it may be worth quickly noting here (as opposed to a later numbered “thing”) that a NULL character (0x0000) does not implicitly end a String.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: