OneBite.Dev - Coding blog in a bite size

Trim A String In C#

Code snippet for how to Trim A String In C# with sample and detail explanation

Simply understanding the concept of trimming a string can be difficult in C#. This article aims to provide an easy walkthrough to learn how to trim a string in C# programming language, with a detailed explanation.

Code Snippet: Trimming a String in C#

Here’s a simple C# program that demonstrates how to trim a string.

using System;

namespace CaveofProgramming 
{
    class Program 
    {
        static void Main(string[] args) 
        {
            string str = "  Hello, World!  ";
            string trimmedStr = str.Trim();
            Console.WriteLine("Before trimming: '{0}'", str);
            Console.WriteLine("After trimming: '{0}'", trimmedStr);
        }
    }
}

When you run this program, it will print:

Before trimming: '  Hello, World!  '
After trimming: 'Hello, World!'

Code Explanation for Trimming a String in C#

Let’s break down the given code snippet and understand how each segment of the code contributes to the main function of trimming a string in C#.

  1. Firstly, we have the line using System;. The System namespace contains fundamental classes and base classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. In our case, it gives us access to the String class which contains the Trim() function.

  2. Next, we define a new namespace “CaveofProgramming” and class “Program” within this namespace.

  3. Inside the Main() function, we declare a string variable str and assign it the value ” Hello, World! ” with leading and trailing white-spaces.

  4. The line string trimmedStr = str.Trim(); is where the trimming happens. The Trim() function is a built-in function in C# and used to remove all leading and trailing white-spaces from the current string. We assign the result of this operation to a new variable trimmedStr.

  5. Finally, Console.WriteLine("Before trimming: '{0}'", str); and Console.WriteLine("After trimming: '{0}'", trimmedStr); print the string before and after the trimming action.

Running this code will then provide you with a practical depiction of how the trim function works, demonstrating the removal of the unnecessary white spaces before and after the initial string.

c-sharp