Remove (Replace) one digit from number in C# and VB.Net

Last Reply 3 months ago By dharmendr

Posted 3 months ago

I need to write function by C# that given Integer N return Possible value obtainable by deleting one '5' digit from decimal representation of N.

it is guaranteed that N will contain at least one '5' digit

Given N=15958, the function should return 1958

Given N=-5859, the function should return -589

Given N=-5000, the function should return 0

because after remove 5 from digit will give me multiple 0 so value will be 0

assume that N is integer within range [-999,995 and 999,995]

N will contain at least one '5' digit on decimal representation

N consist at least two digits on decimal representation

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Hi ahmedsa,

Refer below code.

C#

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(RemoveNumber(15958, '5').ToString());
}
private decimal RemoveNumber(decimal number, char value)
{
    int index = number.ToString().IndexOf(value);
    number = Convert.ToDecimal(number.ToString().Remove(index, 1));
    return number;
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Response.Write(RemoveNumber(15958, "5"c).ToString())
End Sub

Private Function RemoveNumber(ByVal number As Decimal, ByVal value As Char) As Decimal
    Dim index As Integer = number.ToString().IndexOf(value)
    number = Convert.ToDecimal(number.ToString().Remove(index, 1))
    Return number
End Function