Lots of logical ORs

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

There has got to be a better way to do this.

Say you want to see if a character entered is 0-9.

You would write code like

if(char_entered == '0' || char_entered == '1' || char_entered == '2' ...)
{
   puts("Hah, you entered a character that looks like a number");
}
'

Is there a way you can do the same thing (in any language) without listing every single character? I know I could use a case (switch) structure too, but that would be harder I think.

timjpriebe's picture

He has: 2,667 posts

Joined: Dec 2004

Two words: Regular expressions.

The specifics would depend on what language you end up using. But you'll end up with something more like (this is pseudo-code):

if (char_entered =~ /[0-9]/)
{
  puts{"Looks like a number");
}
'

He has: 1,758 posts

Joined: Jul 2002

in php you would do:

if(is_numeric($char)) {
    echo("it's a number!");
}
'

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.