[C#] Remove Last Character From String

[C#] Remove Last Character From String C# and Vb.net Remove last character from string example

Here we will see how to remove last character from string. As a developer you may come across situation, where you would like to remove last character from string. We will see both C#.net and VB.net example. Trick is very simple. we will use Asp.net demo project with C# to remove last character.

Code:

protected void Page_Load(object sender, EventArgs e)
  {
    string inputString = "This is input string.";
    // Let's remove last . character from input string.
    int length = inputString.Length;
    string outputString = inputString.Remove(length - 1, 1);
    
    Response.Write(outputString);
    
  }

VB.net example remove last character from string.

Protected Sub Page_Load(sender As Object, e As EventArgs)
	Dim inputString As String = "This is input string."
	' Let's remove last . character from input string.
	Dim length As Integer = inputString.Length
	Dim outputString As String = inputString.Remove(length - 1, 1)

	Response.Write(outputString)

End Sub

Remove last 2 characters from string.

protected void Page_Load(object sender, EventArgs e)
  {
    string inputString = "This is input string.";
    // Let's remove last 2 characters from input string.
    int length = inputString.Length;
    string outputString = inputString.Remove(length - 2, 2);
    
    Response.Write(outputString);
    
  }

Let’s see C# console application which removes last and first comma character from given string. Here we will use Trim function.

void Main()
{
    string inputText = "This is string ending with comma character,";
    
    string result = inputText.Trim(",".ToCharArray());
    
    Console.WriteLine(result);
    
}

VB.net program to remove last and first characters from given string using Trim function.

Private Sub Main()
	Dim inputText As String = "This is string ending with comma character,"

	Dim result As String = inputText.Trim(",".ToCharArray())

	Console.WriteLine(result)

End Sub

Tags:

C# DateTime ToString()Replace string in C#C# Remove Trailing Comma Spaces And ZerosSplit String In C#c# stringC# foreach loopc# string first character uppercaseHow To Declare and access array of string in C#.net String vs stringC# Get Character from StringAsp.net Convert String To Image

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.