TechieClues TechieClues
Updated date Feb 22, 2021
In this code snippet, we will see how to identify if a string is numeric or not in C#. This code snippet helps for the fresh or experienced C# developers.
  • 1.1k
  • 0
  • 0

In this code snippet, we will see how to identify if a string is numeric or not in C#. This code snippet helps for the fresh or experienced C# developers.

Using Regular Expression:

Example 1: Give input is numeric

using System;
using System.Text.RegularExpressions;

namespace SampleApp
{
    class FindNumeric
    {
        public static void Main()
        {
            var regex = new Regex(@"^\d+$");
            var str = "1000";

            if (regex.IsMatch(str))
            {
                Console.WriteLine("This is a numeric value");
            }
            else
            {
                Console.WriteLine("This is not a numeric value");
            }
            Console.ReadKey();
        }
    }
}

Output: 

This is a numeric value

Example 2: Give input is non-numeric

using System;
using System.Text.RegularExpressions;

namespace SampleApp
{
    class FindNumeric
    {
        public static void Main()
        {
            var regex = new Regex(@"^\d+$");
            var str = "TechieClues";

            if (regex.IsMatch(str))
            {
                Console.WriteLine("This is a numeric value");
            }
            else
            {
                Console.WriteLine("This is not a numeric value");
            }
            Console.ReadKey();
        }
    }
}

Output:

This is not a numeric value

Using Enumerable.All Method

Example:

using System;
using System.Linq;

namespace SampleApp
{
    class FindNumeric
    {
        public static void Main()
        {   
            var str = "1000";
            if (str.All(char.IsDigit))
            {
                Console.WriteLine("This is a numeric value");
            }
            else
            {
                Console.WriteLine("This is a not a numeric value");
            }
                        
            var str1 = "TechieClues";
            if (str1.All(char.IsDigit))
            {
                Console.WriteLine("This is a numeric value");
            }
            else
            {
                Console.WriteLine("This is not a numeric value");
            }

            Console.ReadKey();
        }
    }
}

Output:

This is a numeric value
This is not a numeric value

 

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!