Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# String Split() Method
Next article icon

C# String Trim() Method

Last Updated : 10 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

C# Trim() is a string class method. This method is used to remove all leading and trailing white-space characters from the current String object and return a new modified string. This method is beneficial for clearing the unwanted extra spaces from the string.

Example 1: Using the Trim() method to remove the leading and the trailing whitespaces from the string.

C#
// C# program to demonstrate the trim method  using System;   class Geeks  {  	public static void Main()  	{ 		// Original string  		String s = "   GeeksForGeeks ";   		// String before removing whitespaces 		Console.WriteLine($"Original string: '{s}'");   		// Applying Trim() method 		string res = s.Trim();          		// New string after removing whitespaces 		Console.WriteLine($"After Trim() method: '{res}'"); 	}  }  

Output
Original string: '   GeeksForGeeks ' After Trim() method: 'GeeksForGeeks' 

Explanation: In the above example, we created a string which contains some extra leading and trailing white spaces which can be removed by the trim method as shown in the output if doesn’t pass any argument it removes all trailing and leading spaces as shown in the output.

Syntax of String Trim() Method

This method can be overloaded by passing different arguments:

public string Trim()

public string Trim(char trimChar)

public string Trim (params char[] trimChars)

Parameters:

  • trimChar(Optional): The specific character which we want to remove from the string.
  • trimChars(Optional): It is the array of characters including the characters which we want to remove from the string either they are leading or trailing.

Return Type:

  • It returns a new modified string the type of Trim() method is System.String.

Note: Null and White Space will not remove automatically if they are not specified in the arguments list.


Example: 2: Removing trailing and leading spaces from string using the Trim() method without passing any argument.

C#
// C# program to illustrate the  // method without any parameters  using System;   class Geeks  {  	public static void Main()  	{  		string s1 = "     GFG";  		string s2 = "   GFG ";  		string s3 = " GFG ";   		// Before Trim method call  		Console.WriteLine("Before:");  		Console.WriteLine(s1);  		Console.WriteLine(s2);  		Console.WriteLine(s3);   		// After Trim method call  		Console.WriteLine("After:");  		Console.WriteLine(s1.Trim());  		Console.WriteLine(s2.Trim());  		Console.WriteLine(s3.Trim());  	}  }  

Output
Before:      GFG    GFG   GFG  After: GFG GFG GFG 

Explanation: In the above example, the Trim() method removes all leading and trailing white-space characters from the current string object. Each leading and trailing trim operation stops when a non-white-space character is encountered. And returns a new modified string.


Example 3: Using the Trim() method with a single character as a parameter to remove trailing and leading characters from a string.

C#
// C# program to illustrate trim(trimChar c) method // with single character parameter using System;   class Geeks  { 	 	public static void Main()  	{ 		 		// String initialization and Declaration 		string s = "GeeksforGeeks";  		// Before trim() method 		Console.WriteLine("Before trim() method: " + s);  		// After trim() method 		Console.WriteLine("After trim() method: " + s.Trim('s'));  	}  }  

Output
Before trim() method: GeeksforGeeks After trim() method: GeeksforGeek 

Explanation: In the above code example, we use the Trim(char trimChar) method which removes the trailing ‘s’ from the given string GeeksforGeeks as shown in the output.


Example 4: Removing different leading and trailing characters from a string using the Trim(char[] trimChars) method with a character array as an argument.

C#
// To illustrate the  // method with parameters  using System;   class Geeks  { 	 	public static void Main()  	{ 		 		// declare char[] array and  		// initialize character 0 to 9  		char[] chars = {'1', '2', '3', '4', '5',  							'6', '7', '8', '9'};  								 		string s1 = "123abc456xyz789";  		Console.WriteLine("Before:" + s1);  		Console.WriteLine("After:" + s1.Trim(chars));   		Console.WriteLine("");   		char[] char2 = { '*', '1', 'c' };  		string s2 = "*123xyz********c******c";  		Console.WriteLine("Before:" + s2);  		Console.WriteLine("After:" + s2.Trim(char2));   		Console.WriteLine("");   		char[] chars3 = { 'G', 'e', 'k', 's' };  		string s3 = "GeeksForGeeks";  		Console.WriteLine("Before:" + s3);  		Console.WriteLine("After:" + s3.Trim(chars3));   		Console.WriteLine("");   		string s4 = "	 Geeks0000";  		Console.WriteLine("Before:" + s4);  		Console.WriteLine("After:" + s4.Trim('0'));  	}  }  

Output
Before:123abc456xyz789 After:abc456xyz  Before:*123xyz********c******c After:23xyz  Before:GeeksForGeeks After:For  Before:	 Geeks0000 After:	 Geeks 

Explanation: In the above example, the Trim() method removes from the current string all leading and trailing characters which are present in the parameter list. Each leading and trailing trim operation stops when a character which is not in trimChars is encountered. As shown in the current string is “123abc456xyz789” and trimChars contains the digits from “1 to 9”, then the Trim method returns “abc456xyz”.

Important Points of Trim() method

  • If the Trim method removes any characters from the current instance, then this method does not modify the value of the current instance. Instead, it returns a new string in which all leading and trailing whitespace characters of the current instance will be removed.
  • If the current string equals Empty or all the characters in the current instance consist of white-space characters, the method returns Empty.


Next Article
C# String Split() Method

M

Mithun Kumar
Improve
Article Tags :
  • C#
  • CSharp-method
  • CSharp-string

Similar Reads

  • C# | Substring() Method
    In C#, Substring() is a string method. It is used to retrieve a substring from the current instance of the string. This method can be overloaded by passing the different number of parameters to it as follows: String.Substring(Int32) Method String.Substring(Int32, Int32) Method String.Substring Metho
    3 min read
  • C# String PadRight() Method
    In C#, the PadRight() is a method of a String class. This method is used to left-align the characters in a String by padding them with spaces or specified characters on the right for a specified total length. Example 1: Using the PadRight() method to add padding to the right of a string. [GFGTABS] C
    4 min read
  • C# String Split() Method
    In C#, Split() is a string class method used to divide a string into an array of substrings. The Split() method divides a string into an array of substrings using specified delimiters. The delimiters can be: A character for example comma(,) or underscore(-). An array of characters char[] or an array
    6 min read
  • C# | TrimStart() and TrimEnd() Method
    Prerequisite: Trim() Method in C# In C#, TrimStart() & TrimEnd() are the string methods. TrimStart() method is used to remove the occurrences of a set of characters specified in an array from the starting of the current String object. TrimEnd() method is used to remove the occurrences of a set o
    3 min read
  • C# String Remove() Method
    In C#, the Remove() method of the String class is used for removing the characters from the specified position of a string. If the length is not specified, then it will remove all the characters after the specified position. This method can be overloaded by changing the number of arguments passed to
    3 min read
  • C# String PadLeft() Method
    The PadLeft() method in C# is a method of the String class. This method is very useful when we want to right-align the string by adding an extra space or padding on the left or the start of the string. It is used to format the text and modify its appearance. This method can be overloaded by passing
    4 min read
  • C# | ToCharArray() Method
    In C#, ToCharArray() is a string method. This method is used to copy the characters from a specified string in the current instance to a Unicode character array or the characters of a specified substring in the current instance to a Unicode character array. This method can be overloaded by changing
    4 min read
  • C# StringBuilder
    StringBuilder is a Dynamic Object. It doesn’t create a new object in the memory but dynamically expands the needed memory to accommodate the modified or new string.A String object is immutable, i.e. a String cannot be changed once created. To avoid string replacing, appending, removing or inserting
    4 min read
  • C# - Different Ways to Find All Substrings in a String
    Given a string as an input we need to find all the substrings present in the given string. Example: Input: geeks Output: g e e k s ge ee ek ks gee eek eks geek eeks geeks Input: ab Output: a b abMethod 1: Using Substring() method We can find all the substrings from the given string using the Substri
    3 min read
  • C# | Char.IsSeparator ( ) Method
    In C#, Char.IsSeparator() is a System.Char struct method which is used to check whether a Unicode character can be categorized as a separator character or not. This method can be overloaded by passing different type and number of arguments to it. Char.IsSeparator(Char) MethodChar.IsSeparator(String,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences