C# - Remove Trailing and Leading Spaces from a String

Learn, how to remove trailing and leading spaces from a string in C#?
[Last updated : March 20, 2023]

Given a string with leading and/or trailing spaces and we have to remove leading or/and trailing spaces using String.Trim() in C#.

String.Trim()

The String.Trim() method returns trimmed string that will contain leading and trailing spaces.

Syntax

String String.Trim();

C# program to remove trailing and leading spaces from a string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      String str1 = " This is a sample string ";
      String str2;

      str2 = str1.Trim();

      Console.WriteLine("Trimmed string is:(" + str2 + ")");

    }
  }

}

Output

Trimmed string is:(This is a sample string)

Explanation

The need of trim is required many times, when we are getting input from the user want save that data into database or use the input data for other purposes. In such case we need trimmed string, that can be getting easily with this method.

C# Basic Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.