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?
YourString = YourString.Remove(YourString.Length - 1);
var input = "12342";
var output = input.Substring(0, input.Length - 1);
or
var output = input.Remove(input.Length - 1);
newString = yourString.Substring(0, yourString.length -1);
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.
That is,
string newStr = sb.Remove(sb.Length - 1, 1).ToString();
To avoid below error:
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.