Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim last character if not a number

Tags:

c#

I'm trying to trim out the last charater from a string if not a number For example : "2+3-4*" From there last astrik needs to be trimmed as it is not a number my result should be as "2+3-4". If user enters "2+3+8" then no needs to trim as the last is number.

like image 454
Venkatesh Konduru Avatar asked Oct 16 '25 14:10

Venkatesh Konduru


2 Answers

You can use this regex: [^0-9]$ to determine if the last character is something other than a number. If the regex is a match, simply remove the last character.

string a = "abc";
if (Regex.IsMatch(a, "[^0-9]$"))
{
  a = a.Remove(a.Length - 1);
}
like image 196
EJoshuaS - Stand with Ukraine Avatar answered Oct 18 '25 07:10

EJoshuaS - Stand with Ukraine


You can check the last char is numeric or not using below snippet:

eg:

string value = "4+8-4*";
int outInt = 0;
bool isLastCharNumeric = int.TryParse(value[value.Length - 1].ToString(), out outInt);
if (!isLastCharNumeric)
{
    //chop off the last char
    value = value.Remove(value.Length - 1;);
}
like image 34
SashaStojanovic Avatar answered Oct 18 '25 08:10

SashaStojanovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!