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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...