Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Okay - I want to convert a LETTER (char) into an NUMBER (int) given a set scheme...

Specifically - when string sInput = "0", "1", "2", "3", "4", "5", "6", "7", "8", and "9" I want to leave it as-is. However if sInput is a letter from "a" to "z" I want to convert it to a NUMBER using the simplest scheme that assign "a"=10, "b"=11, "c"=12, etc... all the way to "z"=35.

I have a working model (as shown in the code below) but I need to cover from 'a' to 'z' and covering all 25 cases as shown below would be ... ugly to say the least...

 

private string ConvertToNumber(string sInput)
{
char[] sOutput = sInput.ToUpper().ToCharArray();

// DO THE CONVERSION SCHEME //
if (sOutput == 'A')
	return "10";
else if (soutput == 'B')
	return "11";
...
...
else
{
	sOutput = sInput;
}
// END OF THE CONVERSION SCHEME //

return sOutput[0].ToString();
}

So I am looking for better ways to accomplish this task, maybe a way to create a for loop (25 times) and somehow increment the character value ???

 

Generally the idea is I have a textbox that allows for 3 characters, I want to add them together to get a total sum but I can't really do 1+a+z so I want to convert a=10 and z=35 so the math becomes 1+10+35=46

Any help would be greatly appreciated, thanks

  • Leaders
Posted

I am kind of confused by your code. You seem to be comparing char arrays to chars... If I understand what you want to acheive, though, this might help:

// You can treat Char values as you would a number.
// For example, you can make comparisons like
// ('A' > 'Z'), which would result in false, since the Unicode
// value of 'A' is less than that of 'Z'. You can also add and 
// subtract chars' unicode values, which is useful for finding 
// how far apart two chars are in terms of Unicode values.

int GetTheValueThatYouWanted(Char c) {
   if(c >= '0' && c <= '9') { // If c is in the range of '0' to '9'
       return (int)c - (int)'0';
       // return the value 0 to 9
   } else if(c >= 'A' && c <= 'Z') { // If c is in the range of 'A' to 'Z'
       return (int)c - (int)'A' + 10; 
       // Subtract 'A' to find out how far in the alphabet it is
       // (A = 0, B = 1...)
       // Add ten to get range of 10-25
   } else if(c >= 'a' && c <= 'z') {
       return (int)c - (int)'a' + 10;
       // Same as above, except lowercase
   } else
       return 0;
}

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...