How to Trim String in C#: Syntax and Examples
In C#, you can trim a string using the
Trim() method, which removes all leading and trailing whitespace characters. You can also use TrimStart() or TrimEnd() to remove whitespace only from the beginning or end of the string respectively.Syntax
The Trim() method removes whitespace from both the start and end of a string. You can also specify characters to remove by passing them as parameters.
string.Trim(): Removes all leading and trailing whitespace.string.TrimStart(): Removes whitespace from the start only.string.TrimEnd(): Removes whitespace from the end only.string.Trim(char[] chars): Removes specified characters from both ends.
csharp
string trimmed = original.Trim(); string trimmedStart = original.TrimStart(); string trimmedEnd = original.TrimEnd(); string trimmedChars = original.Trim(new char[] { '*', ' ' });
Example
This example shows how to use Trim(), TrimStart(), and TrimEnd() to remove spaces and specific characters from a string.
csharp
using System; class Program { static void Main() { string original = " ** Hello World! ** "; string trimmed = original.Trim(); string trimmedStart = original.TrimStart(); string trimmedEnd = original.TrimEnd(); string trimmedChars = original.Trim(new char[] { ' ', '*'}); Console.WriteLine($"Original: '{original}'"); Console.WriteLine($"Trim(): '{trimmed}'"); Console.WriteLine($"TrimStart(): '{trimmedStart}'"); Console.WriteLine($"TrimEnd(): '{trimmedEnd}'"); Console.WriteLine($"Trim(chars): '{trimmedChars}'"); } }
Output
Original: ' ** Hello World! ** '
Trim(): '** Hello World! **'
TrimStart(): '** Hello World! ** '
TrimEnd(): ' ** Hello World! **'
Trim(chars): 'Hello World!'
Common Pitfalls
One common mistake is expecting Trim() to remove characters inside the string or only from one side without using the correct method. Also, Trim() without parameters only removes whitespace, not other characters.
To remove specific characters, you must pass them as a char[] to Trim(), TrimStart(), or TrimEnd().
csharp
string example = "--Hello--"; // Wrong: does not remove dashes string wrongTrim = example.Trim(); // Right: removes dashes from both ends string rightTrim = example.Trim(new char[] { '-' });
Quick Reference
| Method | Description | Removes |
|---|---|---|
| Trim() | Removes whitespace from start and end | Whitespace |
| TrimStart() | Removes whitespace from start only | Whitespace |
| TrimEnd() | Removes whitespace from end only | Whitespace |
| Trim(char[] chars) | Removes specified characters from start and end | Specified characters |
Key Takeaways
Use
Trim() to remove whitespace from both ends of a string.Use
TrimStart() or TrimEnd() to trim only the start or end.Pass a
char[] to Trim() to remove specific characters.Trim() without parameters only removes whitespace, not other characters.Trimming does not remove characters inside the string, only from the edges.