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
  • 771
  • 2
  • 16
  • 37
  • 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

81
YourString = YourString.Remove(YourString.Length - 1);
Habib
  • 219,104
  • 29
  • 407
  • 436
amin
  • 1,194
  • 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,819
  • 9
  • 77
  • 111
123 456 789 0
  • 10,565
  • 4
  • 43
  • 72
4

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

DFord
  • 2,352
  • 4
  • 33
  • 51
2

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.TrimEnd(1); //returns "...Hello"

or chained:

string newString = oldString.Substring(3).TrimEnd(1);  //returns "Hello"
SᴇM
  • 7,024
  • 3
  • 24
  • 41
Andrea
  • 1,838
  • 1
  • 13
  • 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
  • 4,920
  • 17
  • 48
  • 72