18

I have a numeric string, which may be "124322" or "1231.232" or "132123.00". I want to remove the last char of my string (whatever it is). So I want if my string is "99234" became "9923".

The length of string is variable. It's not constant so I can not use string.Remove or trim or some like them(I Think).

How do I achieve this?

Neeraj Kumar
  • 755
  • 2
  • 16
  • 32
  • 6
    `Please Read this carefully And then tell me this question is duplicate` [This is a duplicate](http://stackoverflow.com/questions/3573284/trim-last-character-from-a-string) – Jonesopolis Oct 07 '13 at 18:17
  • Related: http://stackoverflow.com/questions/2776673/how-do-i-truncate-a-net-string – Shog9 Apr 06 '16 at 18:42
  • Possible duplicate of [Delete last char of string](http://stackoverflow.com/questions/7901360/delete-last-char-of-string) – Tor Klingberg Aug 25 '16 at 16:05

5 Answers5

78
YourString = YourString.Remove(YourString.Length - 1);
Habib
  • 212,447
  • 27
  • 392
  • 421
amin
  • 1,134
  • 1
  • 12
  • 20
  • 1
    The important point here is that we need to assign it back to the original string. I lost time because I did not notice it, so maybe helpful to someone else. – Onat Korucu Nov 29 '21 at 13:27
12
var input = "12342";
var output = input.Substring(0, input.Length - 1); 

or

var output = input.Remove(input.Length - 1);
Irvin Dominin
  • 30,447
  • 9
  • 79
  • 109
123 456 789 0
  • 10,482
  • 4
  • 41
  • 69
4

newString = yourString.Substring(0, yourString.length -1);

DFord
  • 2,322
  • 4
  • 35
  • 48
1

If this is something you need to do a lot in your application, or you need to chain different calls, you can create an extension method:

public static String TrimEnd(this String str, int count)
{
    return str.Substring(0, str.Length - count);
}

and call it:

string oldString = "...Hello!";
string newString = oldString.Trim(1); //returns "...Hello"

or chained:

string newString = oldString.Substring(3).Trim(1);  //returns "Hello"
Andrea
  • 1,778
  • 1
  • 12
  • 7
0

If you are using string datatype, below code works:

string str = str.Remove(str.Length - 1);

But when you have StringBuilder, you have to specify second parameter length as well.

SB

That is,

string newStr = sb.Remove(sb.Length - 1, 1).ToString();

To avoid below error:

SB2

Vikrant
  • 5,290
  • 16
  • 48
  • 71