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#?