How to extract the last number from a string in C#

3 Answers

0 votes
using System;
using System.Linq;

class Program
{
    static void Main() {
        string str = "98 c# programming 15";
        
        int number = int.Parse(str.Split().Last());

        Console.Write(number);
    }
}




/*
run:

15

*/

 



answered Aug 30, 2023 by avibootz
0 votes
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main() {
        string str = "98 c# programming15";
        
        string[] arr = Regex.Split(str, @"\D+");
        
        int number = int.Parse(arr[arr.Length - 1]);

        Console.Write(number);
    }
}




/*
run:

15

*/

 



answered Aug 30, 2023 by avibootz
0 votes
using System;
using System.Text.RegularExpressions;

class Program
{
    public static int get_last_number(String str) {
	    string[] arr = Regex.Split(str, @"\D+");

		return int.Parse(arr[arr.Length - 1]);
	}
    static void Main() {
        string str = "98 c# 22 programming15";

        int number = get_last_number(str);

        Console.Write(number);
    }
}




/*
run:

15

*/

 



answered Aug 30, 2023 by avibootz

Related questions

2 answers 158 views
3 answers 285 views
1 answer 173 views
1 answer 127 views
2 answers 117 views
1 answer 138 views
...