Reputation: 13
I have an issue with my code if I type in something like:
an apple
It will give me as output 33 instead of 65, which is the sum of the positions of each letter of that string in the alphabet:
65 = 1+14+1+16+16+12+5
How can I fix that?
static int alphaSum(string letter)
{
int sum = 0;
char c = letter[0];
for (int i = 0; i < letter.Length; i++)
{
c = (char)letter[i];
sum += char.ToUpper(c) - 64;
}
return sum;
}
Upvotes: 2
Views: 143
Reputation: 43890
Your bug is that you are counting an empty space that gives you -32. You can use LINQ
var sum=letter.ToUpper().Where(l=> l>='A' && l<='Z').Select(l =>( (short)l)-64).Sum();
or fix your method
static int alphaSum(string letter)
{
letter=letter.ToUpper();
int sum = 0;
for (int i = 0; i < letter.Length; i++)
{
var c = Convert.ToInt16(letter[i]);
if( c < 65 || c > 90 ) continue;
sum += c-64;
}
return sum;
}
sum
65
Upvotes: 1