C# Trim String Tips
C# Trim String Tips
C# Trim String Tips
http://www.dotnetperls.com/trim 1/8
C# Trim
Trim eliminates leading and trailing
whitespace. We need to remove
whitespace from the beginning or ending
of a string. We use the .NET Framework's
Trim method to do this efficiently. This method removes any
characters specified.
Trim input and output
String input: " This is an example string. "
Trim method result: "This is an example string."
String input: "This is an example string.\r\n\r\n"
Trim method result: "This is an example string."
String input: "\t, again and again."
TrimStart method: "again and again."
Note: You can remove commas, spaces, and tabs.
Example
This first example removes space characters from the beginning and
end of a C# string. Note that when you call Trim on a string, it copies
the string and returns a modified version of that copy. The original is
not changed.
Program that uses Trim: C#
using System;
Go
C#: String
Book Your Air Ticket
Round Trip One Way
*Conditions apply
Going To: Leaving From: Passengers:
1
Depart Date: Return Date:
8 May 2014 May 2014 8
--------------- ---------------
C# String
C# Code
C# Object Memory
8/5/2014 C# Trim String Tips
http://www.dotnetperls.com/trim 2/8
class Program
{
static void Main()
{
// Input string
string st = " This is an example string. ";
// Call Trim instance method.
// This returns a new string copy.
st = st.Trim();
Console.WriteLine(st);
}
}
Output
(Spaces were removed.)
This is an example string.
The Trim method is used with no parameters,
meaning it uses a default set of whitespace characters
to Trim. You can provide an array parameter of chars,
as we see in one of the following examples.
Char Array
Next:
The Console.WriteLine statement prints the copied
string that has no spaces at the beginning or end.
Console.WriteLine
Line breaks
We can remove new lines from strings with Trim(). The Trim method
will remove both UNIX style line breaks and Windows style line
8/5/2014 C# Trim String Tips
http://www.dotnetperls.com/trim 3/8
breaks. This example shows Windows line
breaks, \r\n.
It uses two Console.WriteLine method
calls, each of which format the string they
display. The output is surrounded by
square brackets.
Trim copies the input string,
modifies the copy,
and then returns a new copy.
Another program that uses Trim: C#
using System;
class Program
{
static void Main()
{
// Input string
string st = "This is an example string.\r\n\r\n";
Console.WriteLine("[{0}]",
st);
st = st.Trim();
Console.WriteLine("[{0}]",
st);
}
}
Output
[This is an example string.
8/5/2014 C# Trim String Tips
http://www.dotnetperls.com/trim 4/8
]
[This is an example string.]
Files
We next trim each line from a file. This works well
with StreamReader or other File methods. The
following example demonstrates Trim on each line
in the file. The file contains three lines, each
ending with a space.
The code first uses File.ReadAllLines. Then it
loops through the lines using foreach. Each line is
trimmed. Because all the lines are in memory, the original file is not
changed. Neither is the array returned by ReadAllLines.
File.ReadAllLines
Program that uses Trim with file: C#
using System;
using System.IO;
class Program
{
static void Main()
{
foreach (string line in File.ReadAllLines("file.txt"))
{
Console.WriteLine("[" + line + "]");
string trimmed = line.Trim();
Console.WriteLine("[" + trimmed + "]");
}
// Note:
// In the loop you can use both strings in their
// original forms. No string is actually changed.
// Trim copies the string.
8/5/2014 C# Trim String Tips
http://www.dotnetperls.com/trim 5/8
}
}
Output: example file
[This file ]
[This file]
[Has some ]
[Has some]
[Whitespace you don't want ]
[Whitespace you don't want]
TrimStart, TrimEnd
This site contains a separate article that is
an example of the TrimStart instance
method on the string type in the C#
programming language. Please consult the
article for a detailed discussion of TrimStart and its usage patterns.
TrimStart
Also:
It is useful to call TrimEnd to remove punctuation from the ends of
strings, such as the ending punctuation in a sentence.
TrimEnd
Implementation
Looking in IL Disassembler at the MSIL
code, Trim calls an internal method called
TrimHelper. This contains several loops,
and uses an O(N squared) algorithm. This
means it loops within loops. Finally it calls
8/5/2014 C# Trim String Tips
http://www.dotnetperls.com/trim 6/8
InternalSubString.
IL Disassembler Tutorial
Tip:
If you have to Trim many different chars, it would be faster to use
a lookup table to test if the character is to be removed.
Therefore:
Implementing a custom Trim that uses an array lookup instead
of a nested loop would be faster. This was not benchmarked
here.
Performance
As part of my analysis, I benchmarked how
Trim performs on different kinds of strings.
For example, I benchmarked Trim on a
string that has characters to be trimmed,
against a string that doesn't need changing.
My results were that Trim takes more time when it has more
characters to remove from the source string. This is because it
iterates through the characters until it can't trim any more. No
numbers are available in this document.
Methods
There are other ways you will need to change or replace the
whitespace in your C# strings. For example, you may need to change
whitespace in the middle of strings, not just on the end as you can do
with Trim methods.
8/5/2014 C# Trim String Tips
http://www.dotnetperls.com/trim 7/8
Whitespace
Punctuation is another common character type
we need to trim. This can be challenging with just
the Trim methoda custom array is required.
One alternative is to use looping and the
char.IsPunctuation method.
Remove, Trim Punctuation
Regex
There are other ways to Trim strings,
such as with regular expressions in the
System.Text.RegularExpressions
namespace. These approaches are
documented elsewhere on this site. They tend to be more complex.
Regex Trim
Regex
Summary
We saw many examples and tips for the
Trim method. We found potential
problems with Trim. And we pointed to
various alternatives. As a developer, I
have used Trim in every nontrivial program I have written.
C# Example
8/5/2014 C# Trim String Tips
http://www.dotnetperls.com/trim 8/8
C# Example
C# Tutorial
C# REGEX Tester