C# Trim Function: Complete Guide
In C#, the Trim function is used to remove leading and trailing spaces or specified characters from a string. It can be used in several different ways.
- Trim() method removes the leading and trailing whitespace or blank characters from a string.
Example: string trimmedString = inputString.Trim(); - TrimStart(): Removes leading spaces or whitespace characters from a string.
Example: string trimmedString = inputString.TrimStart(); - TrimEnd(): Removes the whitespace or blank characters at the end of a string.
Example: string trimmedString = inputString.TrimEnd(); - Trim(char[]): Remove characters contained in the specified character array at the beginning and end of the string.
Example: char[] charsToTrim = { ‘ ‘, ‘,’, ‘.’ };
string trimmedString = inputString.Trim(charsToTrim); - Trim(char): to remove specified character from the beginning and end of a string.
Example: string trimmedString = inputString.Trim(‘ ‘);
It is important to note that all of the above functions return a new string with spaces or specified characters removed, without altering the original string.