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.

  1. Trim() method removes the leading and trailing whitespace or blank characters from a string.
    Example: string trimmedString = inputString.Trim();
  2. TrimStart(): Removes leading spaces or whitespace characters from a string.
    Example: string trimmedString = inputString.TrimStart();
  3. TrimEnd(): Removes the whitespace or blank characters at the end of a string.
    Example: string trimmedString = inputString.TrimEnd();
  4. 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);
  5. 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.

bannerAds