Trim a string

Trim, TrimStart, TrimEnd remove specified characters from a string.

TrimStart removes the characters from the start of a string.

TrimEnd deletes the characters from the end of a string.

Trim does the trim from both ends.


using System;

class Sample
{
    public static void Main()
    {
        string s = "     java2s.com       ";
        Console.WriteLine("=" + s.Trim() + "=");
        Console.WriteLine("=" + s.TrimStart() + "=");
        Console.WriteLine("=" + s.TrimEnd() + "=");
    }
}

The output:


=java2s.com=
=java2s.com       =
=     java2s.com=

By default these functions remove while spaces including tabs and new lines.

We can passin characters to those functions.


using System;

class Sample
{
    public static void Main()
    {
        string s = "java2s.com";
        Console.WriteLine("=" + s.Trim('m') + "=");
        Console.WriteLine("=" + s.TrimStart('j') + "=");
        Console.WriteLine("=" + s.TrimEnd('m') + "=");
    }
}

The output:


=java2s.co=
=ava2s.com=
=java2s.co=
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.