ZetCode

C# trim string

last modified November 6, 2026

In this article we show how to trim strings in C# language with String.Trim, String.TrimStart and String.TrimEnd.

The String.Trim method removes all leading and trailing white-space characters from the current string. The overloaded Trim(char) and Trim(params char[]) methods remove all leading and trailing occurrences of the specified characters.

The String.TrimStart method removes all leading and the String.TrimEnd all trailing white-space characters or specified characters from the string.

C# trim string example

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

Program.cs
var word = "\tfalcon  ";

Console.WriteLine($"[{word}] {word.Length}");

var word2 = word.TrimStart();
Console.WriteLine($"[{word2}] {word2.Length}");

var word3 = word.TrimEnd();
Console.WriteLine($"[{word3}] {word3.Length}");

var word4 = word.Trim();
Console.WriteLine($"[{word4}] {word4.Length}");

We have a word with a leading tabulator and two trailing spaces. We call the three trimming methods and check the returned string's length with the Length property. The square brackets make the removed white space visible.

$ dotnet run
[	falcon  ] 9
[falcon  ] 8
[	falcon] 7
[falcon] 6

C# trim returns a new string

Strings in C# are immutable. The trimming methods do not modify the string; they return a new one.

Program.cs
var word = "  falcon  ";

word.Trim();
Console.WriteLine($"[{word}]");

word = word.Trim();
Console.WriteLine($"[{word}]");

var trimmed = word.Trim();
Console.WriteLine(ReferenceEquals(word, trimmed));

A common mistake is to call a trimming method and ignore its return value.

word.Trim();

This call has no effect; the result is thrown away.

word = word.Trim();

We must assign the result back to the variable.

var trimmed = word.Trim();
Console.WriteLine(ReferenceEquals(word, trimmed));

If there is nothing to trim, the method returns the original string instance instead of allocating a copy.

$ dotnet run
[  falcon  ]
[falcon]
True

C# trim and Unicode white space

The parameterless trimming methods remove all characters for which char.IsWhiteSpace returns true. Besides spaces, tabs, and new lines, this includes other Unicode space characters.

Program.cs
string[] samples =
[
    " \t\r\n falcon \n",
    "\u00A0falcon\u00A0",
    "\u3000falcon\u2003",
    "\u200Bfalcon\u200B"
];

foreach (var s in samples)
{
    var t = s.Trim();
    Console.WriteLine($"{s.Length} -> {t.Length}");
}

Console.WriteLine(char.IsWhiteSpace('\u00A0'));
Console.WriteLine(char.IsWhiteSpace('\u200B'));

var cleaned = samples[3].Trim('\u200B');
Console.WriteLine(cleaned.Length);

We trim strings with various kinds of white space.

    "\u00A0falcon\u00A0",
    "\u3000falcon\u2003",

The no-break space (U+00A0), the ideographic space (U+3000), and the em space (U+2003) are white-space characters; they are removed.

    "\u200Bfalcon\u200B"

The zero width space (U+200B) is not considered white space. Such characters often appear in text copied from web pages.

var cleaned = samples[3].Trim('\u200B');

We remove it by passing the character to Trim explicitly.

$ dotnet run
13 -> 6
8 -> 6
8 -> 6
8 -> 8
True
False
6

C# trim specific characters

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

Program.cs
var text = "Look! There is a hawk in the sky. Do you have a camera?";

var words = text.Split(' ').Select(word => word.TrimEnd('?', '.', '!'));
Console.WriteLine(string.Join(' ', words));

var price = "$$$1250.00$";
Console.WriteLine(price.Trim('$'));

var path = "/home/user/docs/";
Console.WriteLine(path.TrimEnd('/'));

var code = "0000123";
Console.WriteLine(code.TrimStart('0'));
Console.WriteLine("0000".TrimStart('0').Length);

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

var path = "/home/user/docs/";
Console.WriteLine(path.TrimEnd('/'));

We remove the trailing slash from a path.

var code = "0000123";
Console.WriteLine(code.TrimStart('0'));
Console.WriteLine("0000".TrimStart('0').Length);

We remove leading zeros. Note that a string consisting of zeros only becomes an empty string.

$ dotnet run
Look There is a hawk in the sky Do you have a camera
1250.00
/home/user/docs
123
0

C# trim is not removing a substring

The characters passed to the trimming methods form a set. The methods remove any of the characters in any order, not a specific substring.

Program.cs
var s = "abcxyzcba";

Console.WriteLine(s.Trim("abc".ToCharArray()));
Console.WriteLine(s.Trim(['c', 'b', 'a']));

var file = "report.txt.txt";
Console.WriteLine(file.TrimEnd(".txt".ToCharArray()));

if (file.EndsWith(".txt"))
{
    Console.WriteLine(file[..^4]);
}

The characters a, b, and c are removed from both ends, regardless of their order.

Console.WriteLine(file.TrimEnd(".txt".ToCharArray()));

Trying to remove a file extension this way is a bug. The method removes the characters ., t, and x from the end until it reaches a different character; it also eats the t of the word report.

if (file.EndsWith(".txt"))
{
    Console.WriteLine(file[..^4]);
}

To remove a suffix, we check it with EndsWith and cut it off with a range. For file names, the Path.GetFileNameWithoutExtension method is a better fit.

$ dotnet run
xyz
xyz
repor
report.txt

C# trim inner white space

The trimming methods do not touch white space inside the string. To collapse multiple inner spaces into one, we need other tools.

Program.cs
using System.Text.RegularExpressions;

var text = "  an   old \t falcon   in  the sky  ";

Console.WriteLine($"[{text.Trim()}]");

var parts = text.Split(' ', '\t').Where(e => e.Length > 0);
Console.WriteLine($"[{string.Join(' ', parts)}]");

var parts2 = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"[{string.Join(' ', parts2)}]");

Console.WriteLine($"[{Regex.Replace(text.Trim(), @"\s+", " ")}]");

We normalize the white space of a text in three ways.

var parts2 = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);

When the separator array is null, Split splits the string on white-space characters. Empty entries between consecutive separators are dropped and the words are joined with a single space.

Console.WriteLine($"[{Regex.Replace(text.Trim(), @"\s+", " ")}]");

A regular expression replaces every run of white-space characters with a single space.

$ dotnet run
[an   old 	 falcon   in  the sky]
[an old falcon in the sky]
[an old falcon in the sky]
[an old falcon in the sky]

C# trim with split options

Since .NET 5, the StringSplitOptions.TrimEntries option trims each substring produced by Split.

Program.cs
var data = " John Doe , gardener ,  1230 \n Roger Roe,driver , 980\n";

var lines = data.Split('\n', StringSplitOptions.RemoveEmptyEntries
    | StringSplitOptions.TrimEntries);

foreach (var line in lines)
{
    var fields = line.Split(',', StringSplitOptions.TrimEntries);
    Console.WriteLine(string.Join('|', fields));
}

We parse comma-separated data with irregular spacing.

var lines = data.Split('\n', StringSplitOptions.RemoveEmptyEntries
    | StringSplitOptions.TrimEntries);

The options can be combined. The lines are trimmed and the empty last line is removed.

$ dotnet run
John Doe|gardener|1230
Roger Roe|driver|980

C# trim user input

Input from users or files often contains surrounding white space. It may also be null or consist of white space only.

Program.cs
string?[] inputs = ["  Paul ", "   ", null, "\tLucy\n"];

foreach (var input in inputs)
{
    if (string.IsNullOrWhiteSpace(input))
    {
        Console.WriteLine("empty input");
        continue;
    }

    Console.WriteLine($"Hello, {input.Trim()}!");
}

string? missing = null;
string name = missing?.Trim() ?? "guest";
Console.WriteLine(name);

We greet users whose names come from an array of inputs.

if (string.IsNullOrWhiteSpace(input))

The string.IsNullOrWhiteSpace method returns true for null, empty, and white-space-only strings. We do not need to trim the string before the check.

string name = missing?.Trim() ?? "guest";

The null-conditional operator calls Trim only on a non-null string; the null-coalescing operator provides a default value.

$ dotnet run
Hello, Paul!
empty input
empty input
Hello, Lucy!
guest

C# trim spans

The ReadOnlySpan<char> type has its own trimming methods. They return a slice of the original memory and do not allocate new strings.

Program.cs
var line = "   key = value   ";

ReadOnlySpan<char> span = line.AsSpan().Trim();

int idx = span.IndexOf('=');

ReadOnlySpan<char> key = span[..idx].Trim();
ReadOnlySpan<char> value = span[(idx + 1)..].Trim();

Console.WriteLine($"[{key}] [{value}]");
Console.WriteLine(key.SequenceEqual("key"));

We parse a key-value pair without creating intermediate strings.

ReadOnlySpan<char> span = line.AsSpan().Trim();

The AsSpan method creates a view of the string; the Trim method narrows the view.

ReadOnlySpan<char> key = span[..idx].Trim();
ReadOnlySpan<char> value = span[(idx + 1)..].Trim();

We slice the span at the equals sign and trim both parts.

$ dotnet run
[key] [value]
True

Source

String.Trim method

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

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all C# tutorials.