ZetCode

C# trim string

last modified July 5, 2020

C# trim string tutorial shows how to trim strings in C# language with String.Trim, String.TrimStart and String.TrimEnd. C# tutorial is a comprehensive tutorial on C# language.

The String.Trim() method removes all leading and trailing white-space characters from the current string. The overloaded String.Trim(Char[]) method removes all leading and trailing occurrences of a set of characters specified in an array from the current string.

The String.TrimStart method removes all leading and the String.TrimEnd all trailing characters or set of characters from the string.

C# trim string example

In the first example, we remove all the leading and trailing white spaces.

Program.cs
using System;

namespace StringTrimEx
{
    class Program
    {
        static void Main(string[] args)
        {
            var word = "\tfalcon  ";

            Console.WriteLine(word.Length);

            var word2 = word.TrimStart();
            Console.WriteLine(word2.Length);

            var word3 = word.TrimEnd();
            Console.WriteLine(word3.Length);

            var word4 = word.Trim();
            Console.WriteLine(word4.Length);
        }
    }
}

We have a word with a leading tabulator and trailing two spaces. We call the three trimming methods and check the returned string's length with the Length property.

C# trim string example II

In the following example, we trim trailing non-whitespace characters from the words.

Program.cs
using System;

namespace StringTrimEx2
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = "Look! There is a hawk in the sky. Do you have a camera?";

            var words = text.Split(' ');

            Array.ForEach(words, word => {

                Console.WriteLine(word.TrimEnd(new char[] {'?', '.', '!'}));
            });
        }
    }
}

We cut the sentence into words with Split. Then we remove the trailing ?, !, and . characters from the words with the TrimEnd method.

In this tutorial we have trimmed strings in C# language.

Read C# tutorial or list all C# tutorials.