How to Trim a String in C#/CSharp

To trim a string in C#/CSharp, we make use of Trim() method.  This will remove any extra space before and after the string.  Example is given.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
namespace Hello_World
{
class Program
{
static void Main(string[] args)
{
string hello = " Hello World ";
Console.WriteLine("Before: " + hello );
Console.WriteLine("After: " + hello.Trim());
}
}
}
using System; namespace Hello_World { class Program { static void Main(string[] args) { string hello = " Hello World "; Console.WriteLine("Before: " + hello ); Console.WriteLine("After: " + hello.Trim()); } } }
using System;

namespace Hello_World
{

    class Program
    {
        static void Main(string[] args)
        {
            string hello = "          Hello World      ";                  

            Console.WriteLine("Before: " + hello );

            Console.WriteLine("After: " + hello.Trim());

        }
    }
}