C# - How to remove last character from string in C#

Scenario: Download Script

You are working as C# or dot net developer, you are writing a program in which you need to remove last character from string values.

There could be different scenarios
Let's say you have a folder path and you don't want the \ at the end
you have a string that always come with comma (,) at the end and you don't need comma at the end
You have the address that always come with address 1, address 2 or address 3. You need to remove last characters.


You can use TrimEnd Method to remove last character if you are aware of the character, as I did in below examples to remove "\" and comma ",". If you are not aware of the last character, you can use Substring method to remove last character from string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TechBrothersIT.com_CSharp_Tutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            //string with \ at the end, need to remove
            string Folderpath = @"C:\Source\";
            //string with comma ( , ) at the end, need to remote
            string Name = "Welcome to TechBrothersIT.com,";

            //Use the TrimEnd to remove last character from string
            string Folderpathtrimed=Folderpath.TrimEnd('\\');
            string NameTrimed = Name.TrimEnd(',');


            //Let's say if we are not sure about the last character but always want to remove
            string Address = "This is test address 1";
            string AddressTrimed = Address.Substring(0, Address.Length - 1);
           
            //Print the values to check if last character is removed
            Console.WriteLine("FolderPath variable value:" + Folderpath);
            Console.WriteLine("FolderPathtrimed variable value:" + Folderpathtrimed);
            Console.WriteLine("Name variable value:" + Name);            
            Console.WriteLine("NameTrimed variable value:" + NameTrimed);
            Console.WriteLine("Address variable value:" + Address);
            Console.WriteLine("AddressTrimed variable value:" + AddressTrimed);
            Console.ReadLine();
        }
    }
}

Here are the output from Console Application before and after removing last characters from string.
How to trim last character from string in C#

1 comment:

  1. Basketball Stars Unblocked is an HTML5 basketball game that you can play for free. It is a fast-paced, arcade-style game with simple controls and addictive gameplay.

    ReplyDelete