C# Tips & Tricks #25 – Find and Extract Number from string

Assume that you have a string in C# and you will need to extract the number from it, You can use the below C# code snippet to do it.

How to find and extract number from a string in C#?

using System;
public class DeveloperPublish {
    public static void Main() {
        string input = "str 165test";
        string output = string.Empty;
        int val=0;

        for (int i=0; i< input.Length; i++)
        {
            if (Char.IsDigit(input[i]))
                output += input[i];
        }

        if (output.Length>0)
            val = int.Parse(output);
        Console.WriteLine(val);
    }
}

Output

How to find and extract number from a string in C#?

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...