O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Trimming Whitespace

You often (but not always) want to trim whitespace from the beginning and/or end of a piece of text; especially user-provided text. When storing data in a SQL database, for example, it is frequently desirable to trim this whitespace.

With that in mind, the framework provides us with the Trim, TrimStart, and TrimEnd methods. Example 10-77 uses Trim to remove the whitespace at the start and end of every line.

Example 10-77. Trimming whitespace

foreach (string line in strings)
{
    if (line != null)
    {
        string trimmedLine = line.Trim();
        if (trimmedLine.Length != 0)
        {
            output.AppendLine(trimmedLine);
        }
        else
        {
            System.Diagnostics.Debug.WriteLine(
                "Found a blank line (after trimming)");
        }
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("Found a null line");
    }
}

Notice how we’re trimming the line once, and storing a reference to the result in a variable, then using that trimmed string in our subsequent tests. Because we’re calling a method on our string instance, we need to test it for nullness before we do that, or we’ll get a null reference exception. This means that we don’t need to call IsNullOrEmpty in our later test. We know that it cannot be null. Instead, we do a quick test for emptiness. It turns out that the most efficient way to do this is not to compare against String.Empty but to check the Length of our string.

If we build and run this, we see the following output:

To be, or not to be--that is the question: Whether 'tis nobler in the mind to suffer, The slings and arrows ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required