C# - Extract Only Numbers from a String

Given a string that contains numbers also, we have to extract only numbers from a string using the String.Split() metho using C# program?
Submitted by Nidhi, on October 10, 2020 [Last updated : March 21, 2023]

Here we extract number from a given string using the Split() method of Regex class with the help of regular expressions.

C# program to extract only numbers from a string using the String.Split()

The source code to extract only numbers from a specified string using the Split() method in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to extract only numbers from a 
//specified string using Split() method

using System;
using System.Text.RegularExpressions;

class SplitDemo
{
    static void Main()
    {
        string[] numbers;
        string str = "Cow has 4 legs, one cow may produce approx 10 ltr milk per day";
        
        numbers = Regex.Split(str, @"\D+");

        Console.WriteLine("Numbers in given string:");
        foreach (string num in numbers)
        {
            Console.WriteLine(num);
        }
    }
}

Output

Numbers in given string:

4
10

Press any key to continue . . .

Explanation

Here, we created a SplitDemo class that contains the Main() method. The Main() method is the entry point of the program. Here we created a string str initialized with a sentence.

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

The Split() method extract data based on specified regular expression, here we extract only digits from the specified string. And then printed the extracted numbers using the "foreach" loop on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.