如何删除C#中String的最后一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19231746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:28:14  来源:igfitidea点击:

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

c#stringtrim

提问by

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".

我有一个数字字符串,可能是"124322"or"1231.232""132123.00"。我想删除我的字符串的最后一个字符(无论它是什么)。所以我想如果我的字符串"99234"变成"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).

字符串的长度是可变的。它不是恒定的,所以我不能使用 string.Remove 或 trim 或类似的东西(我认为)。

How do I achieve this?

我如何实现这一目标?

采纳答案by amin

YourString = YourString.Remove(YourString.Length - 1);

回答by DFord

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

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

回答by 123 456 789 0

var input = "12342";
var output = input.Substring(0, input.Length - 1); 

or

或者

var output = input.Remove(input.Length - 1);

回答by Vikrant

If you are using stringdatatype, below code works:

如果您使用string数据类型,以下代码有效:

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


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

但是当你有时StringBuilder,你还必须指定第二个参数length

SB

SB

That is,

那是,

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

To avoid below error:

为避免以下错误:

SB2

SB2

回答by Andrea

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"