Strings and StringBuilders
I will expect you will have a great deal of familiarity with strings at this point. Declaring them, initializing
them, changing their values, using string methods, "tokenizing a string", etc. What I'm going to cover here are
instead some of the unique things that C# introduces to how strings store characters (Unicode!) and what the
StringBuilder does for us.
The fact that strings in C# store the characters as 2-byte Unicode characters allows us expansion into the
character set beyond just ASCII. If you thought it was fun having access to 256 characters (including a bunch of
non-printable characters), just wait til you're tinkering around with 65,536 characters, including emoji's!
Unicode values can be specified as \udddd or \xdddd where "dddd" is the four-digit hexadecimal code for that
character. For example, \u03B1 is α (lowercase Greek letter "alpha") and \x2623 is the universal symbol
for anyone who thinks their preferred programming language makes them superior to other computer programmers:
☣
Here are some notable features of string usage in C#:
string empty = "";
string but_why = System.String.Empty; // Uses the "Empty" constant instead of ""
string escapes_make_me_mad = "c:\\My Documents\\My Memes\\gru_debugging.jpg";
string this_is_much_better = @"c:\My Documents\My Memes\gru_debugging.jpg";
// The @ avoids the necessity of prefixing escape characters with \
char[] message = { 'd', 'e', 'a', 'd', 'l', 'i', 'f', 't' };
string convert = new string(message);
convert[0] = 'D'; // This, however, is not legal. "strings" are immutable
if (alpha < beta) // Generates a compilation error, as relational operators don't work for strings
if (alpha.CompareTo(beta) < 0) // instead, we do this for <
if (alpha.CompareTo(beta) == 0) // this for equality
if (alpha.CompareTo(beta) > 0) // and this for >
You can also construct strings from other variable types, using a callback to old C-style inclusions of
variables in print statements:
int minutes = 525600;
string rent = String.Format("{0} moments so dear.", minutes}; // This replaces {0} with the value of minutes
As mentioned briefly above, strings are immutable — they can be assigned any
value you like, and re-assigned new values if they aren't declared as const or
readonly, but you cannot change individual elements of the string. If you need to do
this, you need to use StringBuilder instead.
StringBuilder changes = new StringBuilder(convert); // "deadlift"
changes.Replace('d', 'D', 0, 1); // Swap the 'd' character found at the beginning with 'D'
changes.Append(" is the best!"); // "Deadlift is the best!" (Do you even lift, bro?)
As you might have guessed, you will want to use StringBuilder whenever you
expect to make a great number of changes to the content of a particular string, albeit at the
expense of some extra memory used to store that string. string is best for
all other occasions, though.