Find Largest or Biggest Number from a String in C#

In one of the interviews, I have one simple requirement: find the largest or biggest number from a given string in C#. We can accomplish this by using Regex.Split() method as shown below.

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleAppExp
    class Program
        static void Main()
            string str = "av2sdyuassbdu1212asm896722ndksad1945324ias";

            var val = Regex.Split(str, @"\D+");

            val = val.Where(s => !string.IsNullOrEmpty(s.Trim())).ToArray();

            int[] myInts = Array.ConvertAll(val, s => int.Parse(s));

            Console.WriteLine("Biggest Numeric Value:" + myInts.Max());

Here we are using Regex expression \D+ to find the numbers from the string. Regex.Split(str, @"\D+") returns string array of numeric values. This string array can have empty values. Exclude empty values from the string array and convert this string array into an int array. From the int array, find the biggest value using Max() method. From the given input, it displays the output as 1945324.

Add comment