What is the difference between Trim() and TrimStart() methods in C#?


Trim

A string method that removes all the leading and trailing whitespaces in a string.

For example, the string “jack sparrow“ would be returned as the following without leading and whitespaces using trim().

jack sparrow

The following is an example −

Example

 Live Demo

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         string str = " Amit ";
         Console.WriteLine(str);

         // trim
         Console.WriteLine("After removing leading and trailing whitespace...");
         string res = str.Trim();
         Console.WriteLine(res);

         Console.ReadKey();
      }
   }
}

Output

Amit
After removing leading and trailing whitespace...
Amit

TrimStart()

The TrimStart() method removes all leading occurrences of a set of characters specified in an array.

Let us see an example to remove all leading zeros −

 Live Demo

using System;
class Program {
   static void Main() {
      String str ="0009678".TrimStart(new Char[] { '0' } );
      Console.WriteLine(str);
   }
}

Output

9678

Updated on: 22-Jun-2020

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements