Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if integer in 3rd position is 5

I am trying to come up with an expression that checks for given integer if its third digit from right-to-left is 5. What I managed so far is this:

string input = "5";

if (Regex.IsMatch(input[2].ToString(), "[5]"))
{
    System.Console.WriteLine("yes");
}
else
    System.Console.WriteLine("no");

Got 2 problems with this:

First it counts from left to the right not from right to the left and second when the number is less than 3 digits like in this case return out of range exception.

like image 772
Filip Stefanov Avatar asked Mar 21 '26 17:03

Filip Stefanov


2 Answers

Use a numerical way. If the number is greater than 99 and n is your integer then use

(n / 100) % 10 == 5

n / 100 removes the last two digits (integer division truncates) and the % 10 extracts the now rightmost digit. Check if it's 5 or not.

It will be much faster than using a regular expression.

like image 191
Bathsheba Avatar answered Mar 24 '26 05:03

Bathsheba


Bathsheba's answer is much better, but if you would like to use a regular expression, I believe this one will fit your needs: ^\d+(?:[5](\d){2})$

like image 32
alvonellos Avatar answered Mar 24 '26 05:03

alvonellos



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!