Home » .Net

How to trim the string in C#, an example of String.Trim() method?

Here, we will learn how to remove trailing and leading spaces from a string in C#.Net? There is a method of string class that is String.Trim() which removes the leading and trailing spaces. In this post we are going to understand with an Example.

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()

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

Syntax:

String String.Trim();

Consider the program:

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)

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.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.