Jump to content

can this be made easier?

- - - - -

  • Please log in to reply
2 replies to this topic

#1
anotheruser

anotheruser

    Learning Programmer

  • Members
  • PipPipPip
  • 44 posts
Do you know how to make this easier:

byte KeyToDigit(char chr)

{

    for (byte i = 1; i < 10; i++)

        if (i.ToString().ToCharArray()[0] == chr)

            return i;

    return 0;

}

it should turn a character into a digit and return zero if it is no digit. What I have now works, but seems needlessly complicated. How can this be made easier?

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
int result;
char character;
Int32.TryParse( character + "" , out result )

The tryparse method should return zero if the parsing fails.
If you want to know if the character was actually zero or it has failed, you can put an if around it as it returns a boolean wether it failed or not.

int result;
char character;
if( Int32.TryParse( character + "" , out result ) )
  //win
else
  //fail


#3
anotheruser

anotheruser

    Learning Programmer

  • Members
  • PipPipPip
  • 44 posts
thanks, that's much simpler.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users