How to Remove the last char of String in C#?
Asked Answered
A

6

22

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?

Agneta answered 7/10, 2013 at 18:14 Comment(3)
Please Read this carefully And then tell me this question is duplicate This is a duplicateSurgery
Related: #2777173Neutral
Possible duplicate of Delete last char of stringSupersensitive
O
85
YourString = YourString.Remove(YourString.Length - 1);
Orography answered 7/10, 2013 at 18:15 Comment(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.Performative
H
14
var input = "12342";
var output = input.Substring(0, input.Length - 1); 

or

var output = input.Remove(input.Length - 1);
Haircut answered 7/10, 2013 at 18:18 Comment(0)
Y
4

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

Yelp answered 7/10, 2013 at 18:18 Comment(0)
S
3

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"
Stlouis answered 30/11, 2018 at 13:12 Comment(0)
I
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

Indurate answered 12/6, 2018 at 6:57 Comment(0)
W
0

string testString = "some string"; testString = testString.TrimEnd(testString.Last()); It will remove the last char from the string

Wallywalnut answered 23/11, 2023 at 8:9 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.