To trim a string in C#, we can use String.Trim method that trims a string from both ends by removing white spaces or a specified character or characters from the start and the end of a string. Code example of string.trim is below.
In .NET and C#, strings are immutable. That means, the method does not update the existing string but returns a new string.
String.Trim()
String.Trim() method has two overloaded forms.
Method | Description |
Trim(Char[]) | Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object. |
Trim() | Removes all leading and trailing white-space characters from the current String object. |
Example
The following example uses Trim methods to trim whitespaces and other characters from a string.
-
- string hello = " hello C# Corner has white spaces ";
-
- Console.WriteLine(hello.Trim());
-
-
- string someString = ".....My name is Mahesh Chand****";
- char[] charsToTrim = { '*', '.' };
- string cleanString = someString.Trim(charsToTrim);
- Console.WriteLine(cleanString);
Listing 1.
The output of Listing 1 looks like Figure 1.
Figure 1.
String.TrimStart()
String.TrimStart() method removes all leading occurrences of a set of characters specified in an array from the current String object.
Example
The following example uses TrimStart methods to trim whitespaces and other characters from the start of a string.
-
- string hello = " hello C# Corner has white spaces ";
-
- Console.WriteLine(hello.TrimStart());
-
-
- string someString = ".....My name is Mahesh Chand****";
- char[] charsToTrim = { '*', '.' };
- string cleanString = someString.TrimStart(charsToTrim);
- Console.WriteLine(cleanString);
Listing 2.
The output of Listing 2 looks like Figure 2.
Figure 2.
String.TrimEnd()
String.TrimEnd() method removes all trailing occurrences of a set of characters specified in an array from the current String object.
Example
The following example replaces all commas with a colon in a string.
-
- string hello = " hello C# Corner has white spaces ";
-
- Console.WriteLine(hello.TrimEnd());
-
-
- string someString = ".....My name is Mahesh Chand****";
- char[] charsToTrim = { '*', '.' };
- string cleanString = someString.TrimEnd(charsToTrim);
- Console.WriteLine(cleanString);
Listing 3.
The output of Listing 3 looks like Figure 3.
Figure 3.