The Trim()
method removes any leading (starting) and trailing (ending) whitespaces from the specified string.
Example
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string text = " Ice cream ";
// trims leading and trailing whitespaces
string s1 = text.Trim();
Console.WriteLine(s1);
Console.ReadLine();
}
}
}
// Output: Ice cream
Trim() Syntax
The syntax of the string Trim()
method is:
Trim(params char[]? trimChars)
Here, Trim()
is a method of class String
.
Trim() Parameters
The Trim()
method takes the following parameter:
- trimChars - an array of characters to remove
Trim() Return Value
The Trim()
method returns:
- a string with leading and trailing whitespace or specified characters removed
Note: In programming, whitespace is any character or series of characters that represent horizontal or vertical space. For example: space, newline \n
, tab \t
, vertical tab \v
etc.
Example 1: C# String Trim()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string text1 = "\n\n\n Ice\ncream \n\n";
string text2 = "\n\n\n Chocolate \n\n";
// trims leading and trailing whitespaces
string s1 = text1.Trim();
Console.WriteLine(s1);
// trims leading and trailing whitespaces
string s2 = text2.Trim();
Console.WriteLine(s2);
Console.ReadLine();
}
}
}
Output
Ice cream Chocolate
Here,
text1.Trim()
returns:
Ice
cream
text2.Trim()
returns:
Chocolate
As you can see from the above example, the Trim()
method only removes the leading and trailing whitespace. It doesn't remove whitespaces that appear in the middle.
Example 2: C# String Trim() - Trim Characters
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// chars to trim
char[] charsToTrim = {'(', ')', '^'};
string text = "(^^Everyone loves ice cream^^)";
Console.WriteLine("Before trim: " + text);
// trims leading and trailing specified chars
string s1 = text.Trim(charsToTrim);
Console.WriteLine("After trim: " + s1);
Console.ReadLine();
}
}
}
Output
Before trim: (^^Everyone loves ice cream^^) After trim: Everyone loves ice cream
Here, we have used the Trim()
method to remove leading and trailing '('
, ')'
, and '^'
characters.
Note: To remove whitespaces or characters between words in a string, you must use Regular Expressions.
Example 3: C# String TrimStart() and TrimEnd()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string text = " Everyone loves ice cream \n\n";
string result;
// trims starting whitespace
result = text.TrimStart();
Console.WriteLine(result);
// trims ending whitespace
result = text.TrimEnd();
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Output
Everyone loves ice cream Everyone loves ice cream
Here,
text.TrimStart()
- removes starting whitespacestext.TrimEnd()
- removes ending whitespaces