c# - How to remove the last character from a string

String remove last character
The following asp.net c# example code demonstrate us how can we remove the last character from a string object programmatically at run time in an asp.net application. String Class Remove() method allow us to get a new string object in which all specified characters (range of characters) are removed/deleted.

String.Remove(Int32) overloaded method return a new string in which all the characters in the current instance, starting at a specified index position to last index position, have been deleted. So, by this overloaded method we can get a new string object, where all characters are deleted from instance string's specified index to last index position.

So, to remove/delete only last character from a specified string object we can use this overloaded method. We just need to pass the beginning index position number of this method as string's last character's index number. So, the method only delete the last character from string.

String object contain zero-based index. String.Length property return the number of characters in a string object. So, we can get the last character index value of a string by accessing String.Length property value minus 1, because string index is zero-based.

Finally, we can remove the last character from a string object programmatically by this way String.Remove(String.Length-1).

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create a string variable.
        string plants = "Meadow Cabbage. California Sycamore. Cart Track Plant";

        Label1.Text = "string of plants..................<br />";
        Label1.Text += plants+"<br />";

        //remove specified substring from string
        string stringWithoutLastChar = plants.Remove(plants.Length-1);

        Label1.Text += "<br />string removed last character...........";
        Label1.Text += "<br />" + stringWithoutLastChar;
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string remove last character</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string remove last character
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string remove last character"  
More c# examples