Help me go to college!
New Discussion Forums!
Join the brand new discussion forums today and help the community grow by contributing
your questions, comments, ideas, and expertise!
Join now!
Google Search
|
String Tips & Tricks in C# How to get the most out of C# strings.
All images, text and code is ©1995-2008 by Alex Franke. All rights reserved. Published: Oct 24, 2006 Updated: Oct 26, 2006
In this article:
Getting Started
Before we get started, I've gotten a number of emails asking what programming books I recommend, and though a
lot of the answer depends upon your specific experience, here are a few best-bets to get you started.
Strings are Immutable
Strings are immutable, which means that they cannot be changed in memory.
So if you, for example, append something to a string, the .Net Framework will
actually reserve memory for a new string of the total desired length and then
copy the original string and the new string into it. So long as the original
strings are still reference, they will not be garbage-collected.
Concatenating Strings
Because strings are immutable, concatenating like the first example below is
not advisable, although it will work.
C# Code
// AVOID this method.
string s = "hello";
s += " there";
s += ", everyone";
// This is better.
StringBuilder sb = new StringBuilder(23); // guess at the length
sb.Append( "hello" );
sb.Append( " there" );
sb.Append( ", everyone" );
Console.WriteLine( sb.ToString() );
// Or this way...
StringBuilder sb = new StringBuilder(23); // guess at the length
sb.Append( "hello" ).Append( " there" ).Append( ", everyone" );
Console.WriteLine( sb.ToString() );
// Or best of all:
String s = "hello there, everyone";
|
Notice that the StringBuilder takes an optional Int32 when it's constructed. (Above I used
23.) It's good practice to make a guess at the total length of the string you'll be creating,
especially if you expect the end result to be a rather short string (less than 100 or so characters).
This is because a StringBuilder, by default, initializes with a total string capacity of 16 bytes, and
it's adjusted automatically (by doubling the capacity) if the string you're building exceeds this
capacity. Adjusting this capacity takes the computer a little extra time, which means that it can actually
be less efficient than the "avoid this" method above for short strings, unless you set the initial
capacity when you construct it.
Strings Are Objects
You can operate on a string literal as an object. You can also index
into a string to retrieve one of its characters Here are a few examples
packed on a single line that results in the string "he...".
C# Code
String s = "hello".Split( "l".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries )[0].PadRight( 5, "m,."[2] );
| String.Format()
This is a fast and efficient way to build complicated strings. Plus it’s easier
to eyeball the string for errors like missing spaces, etc.)
C# Code
String name = "Alex";
int number = 2;
String s = String.Format( "{0} has {1} child{2}.", name, number, (number > 1) ? "ren" : String.Empty );
Console.WriteLine( s );
| Checking for EmptyC# Code
string s = "hello";
// Test if a string is neither null nor empty. This has to be a static
// memeber of the String class because the object may be null!
if ( !String.IsNullOrEmpty( s ) ) ...
// Test if a string is empty.
if ( s.Length != 0 ) ...
// Test if a string is empty. (another way, more explicit way to do it)
if ( s != String.Empty ) ...
// AVOID doing it this way. This causes the Framework to create a new
// blank string before comparing it to the original. This is not efficient.
if ( s != "" ) ... // AVOID THIS METHOD
| Trimming Characters
You can trim any set of characters from a string. This trims different characters from
both the front and the end of the string and writes out "This is a message!".
C# Code
String message = "x This is a message!.:()";
Console.WriteLine( message.TrimStart( "x ".ToCharArray() ).TrimEnd( "().:".ToCharArray() ) );
| Escaping, @, and "\r\n"
A string literal can contain any type of character literal, including escaped
characters. This sets s equal to "Hello c:\" (including the quotation marks).
C# Code
String s = "\"Hello \u0063:\\\"";
|
Use "\r\n" instead of "\n\r" to insert CR/LF character literals
into a string. This inserts the literals in the proper order. You can also use
Environment.NewLine.
You can avoid processing escape sequences with the "@" symbol. Use ""
to insert a single quotation mark. For example, the following sets s to "Hello \u0063:\\"
(including the quotation marks). Note the change in the quotation marks.
C# Code
String s = @"""Hello \u0063:\\""";
| Recommended References
There are tons of books out there about the C# language, but not so many
about the IDE or the .Net Framework itself. Here are a few of my favorites:
|