free hit counter script
plans.theFrankes.com Socialize: Stumble It! Digg It! del.icio.us! reddit! Google bookmark!
Email this pageEmail this page Feed index Feed Index
Skip Navigation Links
Home
Recording StudioExpand Recording Studio
Alibre DesignExpand Alibre Design
CodeExpand Code
WoodworkingExpand Woodworking
Et CeteraExpand Et Cetera
Skip Navigation LinksHome : Code : Programming Tutorials : String Tips & Tricks in C#
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.

C# Programming Books for Beginners - Click to learn more
Microsoft C# Programming for the Absolute Beginner (For the Absolute Beginner (Series).)
C#: A Beginners Guide
$26.99
Learning C# 2005: Get Started with C# 2.0 and .NET Programming (2nd Edition)
$26.39
Visual C# 2005 How to Program (2nd Edition) (How to Program)
$79.69
C# Programming Books for Pros - Click to learn more
C# for Programmers (2nd Edition) (Deitel Developer Series)
$47.03
The Dark Art of C# Programming: .Net Core Language (Series)
$19.95
Code Complete: A Practical Handbook of Software Construction
$31.49
C# Text Manipulation Handbook

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 Empty

C# 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:

Visual Studio IDE Books - Click to learn more
Visual Studio .NET Tips and Tricks
$14.35
Professional Visual Studio 2005
$31.49
Microsoft Visual Studio 2005 Unleashed
$37.79
Advanced .Net References - Click to learn more
Professional .NET Framework 2.0 (Programmer to Programmer)
$26.39
.NET Framework Standard Library Annotated Reference, Volume 1: Base Class Library and Extended Numerics  Library (Microsoft .NET Development Series)
.NET Windows Forms in a Nutshell
$34.16
.NET Framework Solutions: In Search of the Lost Win32 API
$50.99
Inside Microsoft  .NET IL Assembler

Copyright 2008 by Alex Franke.
All rights reserved. Email: alex at thefrankes dot com
This page and all site content, including downloadable plans, tutorials, images and code are
copyright 1987-2008 by Alex Franke unless otherwise noted. All rights reserved.
Plans may not be used for commercial purposes without express written permission.