patio87

How can I do a check to see if what is entered into a console.readline() is a word/letter, or a number


Re: Visual C# General Testing input

Daniel Kuppitz

Code Snippet

using System;

using System.Text.RegularExpressions;

namespace ConsoleApplication1

{

class Program

{

static Regex wordRegex = new Regex(@"^\w+$");

static Regex numberRegex = new Regex(@"^\d+$");

static void Main(string[] args)

{

string stringToTest = Console.ReadLine();

if (numberRegex.IsMatch(stringToTest))

Console.WriteLine("It's a number.");

else if (wordRegex.IsMatch(stringToTest))

Console.WriteLine("It's a word/letter.");

else

Console.WriteLine("It's something, I did not expect.");

Console.ReadLine();

}

}

}

--

Regards,

Daniel Kuppitz





Re: Visual C# General Testing input

patio87

Awesome reply, I will hold onto that for future reference I promise. Is there a simpler way for this I am in a class and I have to write a simple app that does this, but I know that they're not expecting something this sophisticated as it is not something we have learned.




Re: Visual C# General Testing input

Daniel Kuppitz

Well, maybe something like this:

Code Snippet

using System;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

int number;

string stringToTest = Console.ReadLine();

if (int.TryParse(stringToTest, out number))

Console.WriteLine("It's a number.");

else

Console.WriteLine("It's a word/letter.");

Console.ReadLine();

}

}

}

or that:

Code Snippet

using System;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

bool isNumber = true;

string stringToTest = Console.ReadLine();

foreach (char c in stringToTest)

isNumber &= (c >= '0' && c <= '9');

if (isNumber)

Console.WriteLine("It's a number.");

else

Console.WriteLine("It's a word/letter.");

Console.ReadLine();

}

}

}

Both variants will tell you "It's a word/letter." when you enter more than one word or nothing.

--

Regards,

Daniel Kuppitz