C# .Trim()

Sriparno08's avatar
Published Dec 6, 2024
Contribute to Docs

In C#, the .Trim() method trims starting and ending whitespaces from a given string.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
    • Beginner Friendly.
      15 hours

Syntax

str.Trim()
  • str: The string from which starting and ending whitespaces are to be removed.

Example

The following example demonstrates the usage of the .Trim() method:

using System;
public class Example
{
public static void Main()
{
string str = " Codecademy ";
// Using the Trim() method
string trimmedStr = str.Trim();
// Printing the results
Console.WriteLine($"Original: '{str}'");
Console.WriteLine($"Trimmed: '{trimmedStr}'");
}
}

The above code produces the following output:

Original: ' Codecademy '
Trimmed: 'Codecademy'

Codebyte Example

The following codebyte example shows the use of the .Trim() method:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C# on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
    • Beginner Friendly.
      15 hours