Determine if string contains only integer values - C# code please

Please provide working tested code that will determine if string contains only integer values - C# code please.  Spaces allowed.  Leading 0 allowed.

These would Pass:

note:  "_" represents a space

"_01294"
"01294"
"0_1294"
"_0_1294"
"0_1294_55678"
"0_1294_55678_"
"_0_1294_55678_"
"_"
LVL 5
Tom KnowltonWeb developerAsked:
Who is Participating?
 
Julian HansenCommented:
This should do it
using System;
using System.Text.RegularExpressions;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = " 0 1294 55678 ";

            if (Regex.Replace(input, "[^0-9 ]", "") == input)
                Console.WriteLine("This one is good");
            else
                Console.WriteLine("Nope");
        }
    }
}

Open in new window

0
 
Tom KnowltonWeb developerAuthor Commented:
Thanks!
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Using int.TryParse(), after removing the spaces:
            string strValue = " 0 1294 55678 ";
            int value;
            if (int.TryParse(strValue.Replace(" ", ""), out value))
            {
                Console.WriteLine("Valid");
            }
            else
            {
                Console.WriteLine("Invalid");
            }

Open in new window

0
 
Tom KnowltonWeb developerAuthor Commented:
Thank you for the follow-up.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.