Convert Letter to Number [C#]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
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...

Code:
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
 
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:
C#:
// 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;
}
 
Back
Top