Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the last number in a string c#?

I have a string that can have values like

"1 Of 1"
"2 Of 4"
"8 Of 10"

etc.

I want the value of the last number in the string, i.e., 1, 4,10.

Would Regex \d+$ work?

like image 445
user3164272 Avatar asked Oct 16 '25 08:10

user3164272


2 Answers

you can use var lastno = input.Split().Last();

like image 132
Damith Avatar answered Oct 17 '25 22:10

Damith


Yes it would but a little cut off at last!

string[] inputs = new[] {"1 Of 1","2 Of 4", "8 Of 10"};
    foreach (var input in inputs)
       {
         string[] numbers = Regex.Split(input, @"\D+");
         Console.WriteLine("Last Number from input \"{0}\" is: {1}", 
                            input,numbers[numbers.Length-1]);
       }
like image 32
Sunny Sharma Avatar answered Oct 17 '25 22:10

Sunny Sharma



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!